Spring-security自定义过滤器

定义过滤器

public class TokenAuthenticationFilter extends AbstractPreAuthenticatedProcessingFilter  {

    public TokenAuthenticationFilter() {
        this.setCheckForPrincipalChanges(true);
        this.setAuthenticationManager(new AuthenticationManager() {
            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                String token = (String)authentication.getPrincipal();
                if(!StringUtils.isEmpty(token)){
                    User user =  new User(token, "ROLE_USER");
                    user.setAuthenticated(true);
                    return user;
                }else{
                    return null;
                }
            }
        });
    }

    @Override
    protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
        String token = request.getParameter("token");
        if(token == null){
            token = request.getHeader("x-token");
        }
        return token;
    }

    @Override
    protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
        return null;
    }
}

security配置

@Configuration
    public static class WebSecurityConfigurer extends WebSecurityConfigurerAdapter{
        
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .addFilter(new TokenAuthenticationFilter())
                .formLogin()
            .and()
                .logout()
                    .invalidateHttpSession(true)
                    .logoutUrl("/logout").logoutSuccessUrl("/")
                    .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .and()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
            .and()
                .authorizeRequests()
                    .anyRequest().authenticated();
        }
    }

 

posted @ 2017-03-28 17:09  kingsy.lin  阅读(3765)  评论(0编辑  收藏  举报