-
配置类
@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、获取请求头携带的tokenString 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); //放行 }
}
SpringSecurity 实现token 认证
2025/8/21 4:28:51
来源:https://blog.csdn.net/m0_74825074/article/details/145924425
浏览:
次
关键词:SpringSecurity 实现token 认证
版权声明:
本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。
我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com
热文排行
- 电力物联网的电力监控系统
- `git restore` 和 `git checkout` 用于丢弃工作区的改动, `git switch` 和 `git checkout` 用来切换分支
- 《警世贤文》摘抄:处人篇、受恩篇、宽人篇、听劝篇、劝善篇(多读书、多看报、少吃零食多睡觉)
- Android显示系统(08)- OpenGL ES - 图片拉伸
- Vmess协议是什么意思? VLESS与VMess有什么区别?
- 三元组抽取在实际应用中如何处理语义模糊性?
- WPS将文字文档朗读
- 使用 Docker 在 Alpine Linux 下部署 Caddy 服务器
- Rust Web框架怎么选?
- Vue.js 项目部署全解析:从开发到上线的关键旅程题