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的高并发IO原理,阻塞BIO同步非阻塞NIO,异步非阻塞AIO
原文地址: IO读写的基础原理 大家知道,用户程序进行IO的读写,依赖于底层的IO读写,基本上会用到底层的read&write两大系统调用.在不同的操作系统中,IO读写的系统调用的名称可能不完 ...
- PHP博客
创建数据库 用户表 blog_user userid int 用户id username varchar(50) 用户名 password varchar(30) 密码 type tinyint(2) ...
- 为什么大多数IOC容器使用ApplicationContext,而不用BeanFactory
1. 引言 Spring框架附带了两个IOC容器– BeanFactory 和 ApplicationContext. BeanFactory是IOC容器的最基本版本,ApplicationConte ...
- JSON小结【json-lib】
javabean:Address package com.baebae.model; public class Address { private String city; private Strin ...
- wait()系统调用分别演示在父子进程
废话不多说开代码 在父进程调用wait() #include<stdio.h> #include<unistd.h> #include<sys/wait.h> in ...
- martini-拓扑映射
如何为一个新的分子创建拓扑文件? 这是martini应用的关键.http://jerkwin.github.io/2016/08/31/Martini%E5%B8%B8%E8%A7%81%E9%97% ...
- subString引起的index out of range
特别注意!!!低级坑 subString(begin,end) subList()均存在这个问题. 当end>String.size(),则index out of range!!!
- 对udp dns的思考2
上一篇文章写道了udp 使用reuseport 多线程编程!!! 但是有几个问题需要考虑一下: 之前hash使用sip sport dip dport为key, 很正常同一个客户端回hash到同一个s ...
- 与pandas初相识
前一阵子有个同事说,他看不懂从kibana上拉下来的日志,但是又想分析一些数据,感觉很头痛,每次都找开发给他整理一下,但是开发也很忙,要数据的频率也略高,那时候正好我跟这位需求方的项目,负责测试工作. ...
- springboot升级导致文件上传自动配置/tmp目录问题解决
1,..\web\src\main\resources\spring\web-men-applicationContext.xml 保留原有的bean配置 <bean id="mult ...