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); //放行
  }

}

相关推荐
神奇小汤圆5 分钟前
别死记硬背!Java的CountDownLatch 核心原理:AQS state 才是关键
后端
ssshooter16 分钟前
告别 Chat Completions:深度解析 AI 接口新标准 `/v1/responses`
人工智能·后端·开源
武子康17 分钟前
大数据-244 离线数仓 - Hive ODS 层建表与分区加载实战(DataX→HDFS→Hive)
大数据·后端·apache hive
神奇小汤圆17 分钟前
MySQL 时间类型选型避坑:timestamp 和 datetime 该怎么选?
后端
德育处主任27 分钟前
『NAS』一句话生成网页,在NAS部署UPage
前端·javascript·aigc
前端老兵AI29 分钟前
前端工程化实战:Vite + ESLint + Prettier + Husky 从零配置(2026最新版)
前端·vite
bluceli30 分钟前
浏览器渲染原理与性能优化实战指南
前端·性能优化
张元清31 分钟前
Astro 6.0:被 Cloudflare 收购两个月后,这个"静态框架"要重新定义全栈了
前端·javascript·面试
凉拌西红柿32 分钟前
如何用工具定位性能瓶颈
前端
青青家的小灰灰33 分钟前
深入理解 async/await:现代异步编程的终极解决方案
前端·javascript·面试