Spring Security + JJWT 实现 JWT 认证和授权
关于 JJWT 的使用,可以参考之前的文章:JJWT 使用示例
一、鉴权过滤器
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
FilterChain filterChain) throws ServletException, IOException {
String token = httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION);
if(!StringUtils.isEmpty(token)) {
UserInfoModel userInfo = JwtUtil.verifyToken(token, JwtConstant.AIM_ACCESS);
if(userInfo != null) {
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userInfo, null, userInfo.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
二、Spring Security 配置
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
@Autowired
private EntryPointUnauthorizedHandler entryPointUnauthorizedHandler;
@Autowired
private RestAccessDeniedHandler restAccessDeniedHandler;
@Bean
GrantedAuthorityDefaults grantedAuthorityDefaults() {
// 去除 ROLE_ 前缀
return new GrantedAuthorityDefaults("");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and().cors()
.and().csrf().disable();
http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
http.exceptionHandling()
.authenticationEntryPoint(entryPointUnauthorizedHandler)
.accessDeniedHandler(restAccessDeniedHandler);
// 不创建会话
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
其中 EntryPointUnauthorizedHandler 和 RestAccessDeniedHandler 是未认证或未授权异常处理,详细代码可以看源码
三、获取当前登录用户
public class CurrentUserUtil {
public static UserInfoModel getUserInfo() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication != null) {
if(authentication instanceof UsernamePasswordAuthenticationToken) {
return (UserInfoModel)authentication.getPrincipal();
}
}
return null;
}
}
测试代码见 TestController,测试时在请求 Header 中添加 Authorization 即可
完整代码:GitHub
参考:
Spring Security + JJWT 实现 JWT 认证和授权的更多相关文章
- Spring Boot,Spring Security实现OAuth2 + JWT认证
阅读此文,希望是对JWT以及OAuth2有一定了解的童鞋. JWT认证,提供了对称加密以及非对称的实现. 内容源码点我 涉及到源码中两个服务 spring-boot-oauth-jwt-server ...
- Spring Security 入门学习--数据库认证和授权
首先是使用的SpringBoot框架 基础需要的pom以来如下,基础的springboot项目的创建就不一一赘述了. <!--spring web--> <dependency> ...
- Spring Cloud实战 | 最终篇:Spring Cloud Gateway+Spring Security OAuth2集成统一认证授权平台下实现注销使JWT失效方案
一. 前言 在上一篇文章介绍 youlai-mall 项目中,通过整合Spring Cloud Gateway.Spring Security OAuth2.JWT等技术实现了微服务下统一认证授权平台 ...
- Spring Security OAuth2 微服务认证中心自定义授权模式扩展以及常见登录认证场景下的应用实战
一. 前言 [APP 移动端]Spring Security OAuth2 手机短信验证码模式 [微信小程序]Spring Security OAuth2 微信授权模式 [管理系统]Spring Se ...
- 六:Spring Security 中使用 JWT
Spring Security 中使用 JWT 1.无状态登录 1.1 什么是有状态? 1.2 什么是无状态 1.3 如何实现无状态 2.JWT 2.1 JWT数据格式 2.2 JWT交互流程 2.3 ...
- 阶段5 3.微服务项目【学成在线】_day16 Spring Security Oauth2_05-SpringSecurityOauth2研究-搭建认证服务器
3 Spring Security Oauth2研究 3.1 目标 本项目认证服务基于Spring Security Oauth2进行构建,并在其基础上作了一些扩展,采用JWT令牌机制,并自定 义了用 ...
- 基于spring boot2.0+spring security +oauth2.0+ jwt微服务架构
github地址:https://github.com/hankuikuide/microservice-spring-security-oauth2 项目介绍 该项目是一个演示项目,主要演示了,基于 ...
- Spring Security 解析(三) —— 个性化认证 以及 RememberMe 实现
Spring Security 解析(三) -- 个性化认证 以及 RememberMe 实现 在学习Spring Cloud 时,遇到了授权服务oauth 相关内容时,总是一知半解,因此决定先把 ...
- Spring Security 实战干货:客户端OAuth2授权请求的入口
1. 前言 在Spring Security 实战干货:OAuth2第三方授权初体验一文中我先对OAuth2.0涉及的一些常用概念进行介绍,然后直接通过一个DEMO来让大家切身感受了OAuth2.0第 ...
随机推荐
- Java入门(6)
阅读书目:Java入门经典(第7版) 作者:罗格斯·卡登海德 当方法在子类和超类都定义了时,将使用子类的定义:因此子类可以修改,替换或完全删除超类的行为或属性. 关键字super引用对象的上一级超类, ...
- leetcode73:minmum-window-substring
题目描述 给出两个字符串S和T,要求在O(n)的时间复杂度内在S中找出最短的包含T中所有字符的子串. 例如: S ="ADOBECODEBANC" T ="ABC&quo ...
- .NET 5 中的隐藏特性
前言 双十一当天 .NET 5 正式发布带来了很多的新特性和改进,个人觉得非常香,并且花了 10 分钟时间就把自己的 4 个 .NET Core 3.1 的项目升级到了 .NET 5,堪称无痛. 但是 ...
- 【转载】图解Transformer(完整版)!
在学习深度学习过程中很多讲的不够细致,这个讲的真的是透彻了,转载过来的,希望更多人看到(转自-张贤同学-公众号). 前言 本文翻译自 http://jalammar.github.io/illustr ...
- pandas_知识总结_基础
# Pandas 知识点总结 # Pandas数据结构:Series 和 DataFrame import pandas as pd import numpy as np # 一,Series: # ...
- iptables-centos|mysql navicat登陆不上
iptables-centos: vi /etc/sysconfig/iptables service iptables restart ====================== mysql na ...
- 绝对定位元素left、right、top、bottom值与其margin和宽高的关系
绝对定位元素(position: absolute)在其相对定位元素(即文档流中最近的非静态定位祖先元素)中,定位祖先元素的宽度为W,垂直高度为H,则存在以下关系: 元素水平方向 width + le ...
- TP5 RCE
Thinkphp5 RCE 复现 环境: win10+wamp+thinkphp5.1.29 下载地址 源码分析 程序首先跳转到 public目录下的index.php,然后执行 thinkphp/l ...
- Python_自动化测试_项目
<论坛自动化测试项目> 1.自行选择合适的社区 2.功能要求 5个以上,不包含登录页 3.多手动测试 多用selenium IDE 4.生成测试报告,发送邮件 5.计划任务定时完成 6 ...
- 3、Spring Boot日志
1.日志框架 市面上的日志框架:JUL.JCL.Jboss-logging.logback.log4j.log4j2.slf4j.... 日志门面 (日志的抽象层) 日志实现 JCL(Jakarta ...