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

}

相关推荐
han_5 分钟前
JavaScript设计模式(十):模板方法模式实现与应用
前端·javascript·设计模式
Rick19936 分钟前
Spring Boot自动装配原理
java·spring boot·后端
得物技术7 分钟前
立正请站好:一个组件复用 Skill 的工程化实践|得物技术
前端·架构·ai编程
北漂Zachary8 分钟前
Laravel 7.x 新特性全解析
android
我命由我1234511 分钟前
Android Jetpack Compose - 组件分类:布局组件、交互组件、文本组件
android·java·java-ee·kotlin·android studio·android jetpack·android-studio
神奇小汤圆14 分钟前
Elasticsearch 与 JVM:生产环境调优实战指南
后端
攀登的牵牛花16 分钟前
OpenClaw 的内心独白,关于最近很火的Harness?
前端·openai
浩星17 分钟前
electron系列8之Electron + Vue 3:构建现代化桌面应用(下)
前端·vue.js·electron
肌肉娃子18 分钟前
一次 Doris FE CPU 飙高的排障实录:从怀疑 fe.conf 到定位 MyBatis 超长批量 UPSERT
后端
腥辣甜咸18 分钟前
队列?不妨试试pgmq
后端