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

}

相关推荐
FfHUCisI7 分钟前
无锁 Reactor 网络模型与 gnet / evio 架构拆解
服务器·开发语言·后端·golang
weixin_417396839 分钟前
监控画面卡顿与录像缺失:码率、NVR与存储容量的排查顺序
前端·网络·技术·酒店·综合布线·弱电
高频因子挖掘机12 分钟前
从第一行 Python 代码开始,个人量化项目应该先接入历史行情还是实时行情?
后端·github·api
高频因子挖掘机14 分钟前
个人开发者如何高效处理 A 股日 K 线数据?基于 QuantDash 的清洗思路与复权实战
后端·github·api
曹牧24 分钟前
Eclipse 工作空间(Workspace)的默认 JDK 配置
前端
yunwei3726 分钟前
eBPF 实例教程:跟踪 Intel NPU 内核驱动操作
linux·后端·性能优化
其实防守也摸鱼1 小时前
Cylab在线靶场——挑战图书馆初学者指南
服务器·前端·数据库·chrome·安全·网络安全·靶场
高频因子挖掘机2 小时前
股票池代码为什么总有问题?从常见误区到可解释的校验报告
后端·github·api
拆房老料4 小时前
【第四部分:Agentic 智能体设计模式】16. 一个 Prompt 搞不定复杂任务?试试 Prompt Chaining
java·前端·人工智能·设计模式·prompt
考虑考虑9 小时前
nginx路由重写
运维·后端·自动化运维