zoukankan      html  css  js  c++  java
  • 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();
            }
        }
  • 相关阅读:
    移动端前端布局的必看前提
    单词统计
    用户场景分析
    学习进度(九)
    团队项目
    学习进度(二)
    数据可视化
    大二下,学习进度(一)
    求最大子数组的和
    构建之法3
  • 原文地址:https://www.cnblogs.com/kingsy/p/6635789.html
Copyright © 2011-2022 走看看