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

}

相关推荐
C_V_Better11 分钟前
Spring Security 如何防止 CSRF 攻击?
java·开发语言·数据结构·后端·算法·spring·csrf
customer081 小时前
【开源免费】基于SpringBoot+Vue.JS酒店管理系统(JAVA毕业设计)
java·vue.js·spring boot·后端·spring cloud·开源
胖虎11 小时前
Android 布局系列(五):GridLayout 网格布局的使用
android·网格布局·安卓布局·gridlayout
XiaoLeisj2 小时前
【CSS—前端快速入门】CSS 常用样式
前端·css
是一只派大鑫2 小时前
从头开始学SpringMVC—02获取请求参数&向域对象共享数据
java·后端·springmvc
云泽野2 小时前
Pytest之parametrize参数化
android·python·pytest
GISer_Jing2 小时前
[React]Render Props、自定义Hooks和Context API优化详解
前端·javascript·react.js
南城巷陌2 小时前
HTTP 协议的发展历程:从 HTTP/1.0 到 HTTP/2.0
前端·网络·网络协议·http·node.js
咖啡の猫2 小时前
http 模块
后端·node.js
Kevin1712062 小时前
前端依赖nrm镜像管理工具
前端