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

}

相关推荐
开开心心就好几秒前
安卓PDF处理工具,免费无广告零弹窗
android·服务器·开发语言·算法·pdf·ocr
风骏时光牛马2 分钟前
AI_Coding:智能代码创作助手
前端
墨狂之逸才6 分钟前
扫码枪响了,应用却没收到:一次 Android USB 线材问题排查
android
高频因子挖掘机42 分钟前
量化项目的数据架构怎么设计?从第一份行情到可扩展的 Python 研究环境
后端·github·api
考虑考虑8 小时前
JDK26中的Map.ofLazy
java·后端·java ee
剪刀石头布啊9 小时前
vue-react为何要虚拟dom
前端
剪刀石头布啊9 小时前
ahooks常用的一些库,我们使用一下
前端
剪刀石头布啊9 小时前
从git更新本地提交记录到更新已经推送到远端记录
前端
云浪10 小时前
Go 并发实战:从零实现一个高并发安全的任务调度器
javascript·后端·go
苏三的开发日记10 小时前
Docker 启动顺序优化(CentOS / Ubuntu)
后端