SpringSecurity 实现token 认证

配置类

@Configuration

@EnableWebSecurity

@EnableGlobalMethodSecurity(prePostEnabled=true)

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

复制代码
  @Bean
  @Override
  public AuthenticationManager authenticationManagerBean() throws Exception {
      return super.authenticationManagerBean();
  }

  // 由于过滤器 比 servelt 先加载 在这里注入一下 负责  TokenAuthenticationTokenFilter 中redisuntity 
  @Bean
  public TokenAuthenticationTokenFilter getTokenFiter(){
      return new TokenAuthenticationTokenFilter();
  }
  @Override
  protected void configure(HttpSecurity http) throws Exception {
      //http.addFilterBefore(new VerCodeFi    lter("/Login/Login"), UsernamePasswordAuthenticationFilter.class);


      http.addFilterBefore(getTokenFiter(), UsernamePasswordAuthenticationFilter.class);


      http
              .authorizeRequests()
              .antMatchers("/Login/**").permitAll() // 放行Login
              .anyRequest().authenticated() // 所有请求都需要验证
              .and()
              .formLogin() // 使用默认的登录页面
              .and()
              .sessionManagement()
              .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
              .csrf().disable();// post请求要关闭csrf验证,不然访问报错;实际开发中开启,需要前端配合传递其他参数
  }

}
*

定义token 验证过滤器

public class TokenAuthenticationTokenFilter extends OncePerRequestFilter {

复制代码
  @Autowired
  private RedisUtils redisUtils;

  public TokenAuthenticationTokenFilter(){
  }

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
      //1、获取请求头携带的token

      String token = request.getHeader("token");

      if(!StringUtils.hasText(token)){
          //不需要token的路由可以直接放行
          filterChain.doFilter(request,response);
          return;
      }

      Object o =redisUtils.get(token);

      if (o==null){

          response.setStatus(200);

          response.setCharacterEncoding("utf-8");
          response.getWriter().write(JSON.toJSONString(Result.failed(401,"token 非法","")));
          return;
      }

      Map<String,String> maps=new HashMap<>();

      Map Values = JSON.parseObject(o.toString(), maps.getClass());


      Collection<GrantedAuthority> authorities = new ArrayList<>();

      authorities.add(new SimpleGrantedAuthority(Values.get("role").toString()));


      UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(new Userdto(), null, authorities);

      SecurityContextHolder.getContext().setAuthentication(authenticationToken);



      filterChain.doFilter(request,response); //放行
  }

}

相关推荐
AAA修煤气灶刘哥1 分钟前
后台任务跑到一半,Laravel Rust 怎么从断点接着跑?
后端
GuWenyue2 分钟前
z-index 写到 9999 还是被盖住:把层叠上下文的 6 个反例全复现了一遍
前端·css·浏览器
我命由我123452 分钟前
Android 广播 - Android 开机广播实现开机自启应用
android·java·linux·java-ee·kotlin·android studio·android-studio
htzyl2066 分钟前
TypeScript:tsconfig配置误区及详情介绍,让你清清楚楚
前端·typescript
AAA修煤气灶刘哥11 分钟前
SQL 一行没改,ClickHouse 的 JOIN 中间结果怎么从 5 亿行降到 100 万?
后端·sql·性能优化
不服老的小黑哥12 分钟前
0b · M2:服务化 + SSE 流式
前端
stormsha13 分钟前
`Could not create connection to database server`:MySQL 8 连不上,真凶藏在第 4 层
java·后端·mysql
梦曦i14 分钟前
0.9.0 新增页面级 style 支持
前端·uni-app x
不服老的小黑哥15 分钟前
10a · M1:命令行 Agent
前端
疯华整猫16 分钟前
类型全对、tsc 零错误,上线却白屏:AI 时代学 TypeScript,学的是它替不了的那一层
前端·typescript