认证过滤器被重复调用

时间:2015-07-17 03:52:01

标签: spring

我为我的休息api设置了弹簧安全性。这是我休息电话的样本,     GET:http://localhost:8081/dashboard/epic/data。执行,过滤,提供程序和最终onAuthenticationSuccess时会触发。这是问题,而不是在身份验证后执行其余URL,它将返回多次过滤。第二次,request.getRequestUrl将为http://localhost:8081/dashboard

这是我的security-context.xml:

  <http auto-config='false' authentication-manager-ref="authenticationManager" entry-point-ref="authenticationEntryPoint">

    <intercept-url pattern="dashboard/**" access="ROLE_USER" />
    <csrf disabled="true"/>
    <custom-filter position="REMEMBER_ME_FILTER" ref="DashboardFilter"></custom-filter>
</http>


<authentication-manager alias="authenticationManager">
    <authentication-provider ref="DashboardAuthProvider"></authentication-provider>
</authentication-manager>

<beans:bean id="DashboardFilter" class="com.apple.store.dashboard.security.DashboardAuthFilter">
    <beans:property name="authenticationManager" ref="authenticationManager"/>
    <beans:property name="authenticationSuccessHandler">
        <beans:bean class="com.apple.store.dashboard.security.LoginSuccessHandler">


        </beans:bean>
    </beans:property>
</beans:bean>

<beans:bean id="authenticationEntryPoint" class="com.apple.store.dashboard.security.DashboardAuthEntryPoint">
</beans:bean>

<beans:bean id="DashboardAuthProvider" class="com.apple.store.dashboard.security.DashboardAuthProvider">  </beans:bean>

这是我的过滤器

public class DashboardAuthFilter extends AbstractAuthenticationProcessingFilter {
    private static final Logger logger = LoggerFactory.getLogger(DashboardAuthFilter.class);

    public DashboardAuthFilter() {
        //super("/j_spring_cas_security_check");
        super("/**");
    }

    public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response)
            throws org.springframework.security.core.AuthenticationException, UnsupportedEncodingException {
        logger.debug("Inside DashboardAuthFilter:attemptAuthentication method:");
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth!=null ){
            if (auth.isAuthenticated()){
                logger.debug("Previously authenticated.isAuthenticated=true::: Auth details:" +auth);
                return auth;
            }
        }

        String _username = null;
        String _password = null;


        String authHeader = request.getHeader("Authorization");
        if (authHeader != null) {
            StringTokenizer st = new StringTokenizer(authHeader);
            if (st.hasMoreTokens()) {
                String basic = st.nextToken();

                if (basic.equalsIgnoreCase("Basic")) {
                    try {
                        String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
                        logger.debug("Credentials: " + credentials);
                        int p = credentials.indexOf(":");
                        if (p != -1) {
                             _username = credentials.substring(0, p).trim();
                             _password = credentials.substring(p + 1).trim();
                        }
                    } catch (Exception e) {

                    }
                }
            }
        }
        else
            System.out.println("request url is "+request.getRequestURL());

        Authentication authResult = null;
        try {
            if( org.apache.commons.lang.StringUtils.isEmpty(_password)) {
                throw new PreAuthenticatedCredentialsNotFoundException("No username:password..");
            }
            String credentials = "NA";

            //String validateCookieDetails = correctAuthentication(AOSCookie, request);

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(_username+":"+_password, credentials);
            authResult = getAuthenticationManager().authenticate(authRequest);
            logger.debug("Attempted authentication: authResult ::" + authResult.toString());
        } catch (org.springframework.security.core.AuthenticationException e) {
                logger.error("AttemptAuthentication: Not Authenticated : AuthenticationException ....." + e.getMessage());

        } catch (Exception e) {
            logger.error("Exception occured during authentication....." + e.getMessage());
        }
        return authResult;
    }

这是我的提供者:

public class DashboardAuthProvider implements AuthenticationProvider {

    private static final Logger logger = LoggerFactory.getLogger(DashboardAuthProvider.class);


    @Override
    public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
        logger.debug("Inside DashboardAuthProvider: authenticate method +authentication=" + authentication);
        Authentication auth =null;
        final List<GrantedAuthority> grantedAuths = new ArrayList<>();
        grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
        try{
            String[] principalStrArr = ((String)authentication.getPrincipal()).split(":");
            //Convert the authentication principal object to a map

            if (principalStrArr[0].equals("test1") && principalStrArr[1].equals("test1"))
            {
                String username = principalStrArr[0];
                String password = principalStrArr[1];


                final UserDetails principal = new AccessInfo(username, password, grantedAuths);
                auth = new UsernamePasswordAuthenticationToken(principal, password, grantedAuths);

                logger.info("DashboardAuthProvider auth= " + auth);
            }
            else {
                logger.info("Wrong credential");
                return null;
            }
        }catch (Exception e){
            logger.error(
                    "Exception occured in DashboardAuthProvider during authentication",
                    e);
        }
        return auth;

    }

这是我的onAuthenticationSuccess:

public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

            super.onAuthenticationSuccess(request, response, authentication);

    }

0 个答案:

没有答案
相关问题