关于 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

参考:

  1. Spring Security和JWT实现登录授权认证
  2. How do I remove the ROLE_ prefix from Spring Security with JavaConfig?
​

Spring Security + JJWT 实现 JWT 认证和授权的更多相关文章

  1. Spring Boot,Spring Security实现OAuth2 + JWT认证

    阅读此文,希望是对JWT以及OAuth2有一定了解的童鞋. JWT认证,提供了对称加密以及非对称的实现. 内容源码点我 涉及到源码中两个服务 spring-boot-oauth-jwt-server ...

  2. Spring Security 入门学习--数据库认证和授权

    首先是使用的SpringBoot框架 基础需要的pom以来如下,基础的springboot项目的创建就不一一赘述了. <!--spring web--> <dependency> ...

  3. Spring Cloud实战 | 最终篇:Spring Cloud Gateway+Spring Security OAuth2集成统一认证授权平台下实现注销使JWT失效方案

    一. 前言 在上一篇文章介绍 youlai-mall 项目中,通过整合Spring Cloud Gateway.Spring Security OAuth2.JWT等技术实现了微服务下统一认证授权平台 ...

  4. Spring Security OAuth2 微服务认证中心自定义授权模式扩展以及常见登录认证场景下的应用实战

    一. 前言 [APP 移动端]Spring Security OAuth2 手机短信验证码模式 [微信小程序]Spring Security OAuth2 微信授权模式 [管理系统]Spring Se ...

  5. 六:Spring Security 中使用 JWT

    Spring Security 中使用 JWT 1.无状态登录 1.1 什么是有状态? 1.2 什么是无状态 1.3 如何实现无状态 2.JWT 2.1 JWT数据格式 2.2 JWT交互流程 2.3 ...

  6. 阶段5 3.微服务项目【学成在线】_day16 Spring Security Oauth2_05-SpringSecurityOauth2研究-搭建认证服务器

    3 Spring Security Oauth2研究 3.1 目标 本项目认证服务基于Spring Security Oauth2进行构建,并在其基础上作了一些扩展,采用JWT令牌机制,并自定 义了用 ...

  7. 基于spring boot2.0+spring security +oauth2.0+ jwt微服务架构

    github地址:https://github.com/hankuikuide/microservice-spring-security-oauth2 项目介绍 该项目是一个演示项目,主要演示了,基于 ...

  8. Spring Security 解析(三) —— 个性化认证 以及 RememberMe 实现

    Spring Security 解析(三) -- 个性化认证 以及 RememberMe 实现   在学习Spring Cloud 时,遇到了授权服务oauth 相关内容时,总是一知半解,因此决定先把 ...

  9. Spring Security 实战干货:客户端OAuth2授权请求的入口

    1. 前言 在Spring Security 实战干货:OAuth2第三方授权初体验一文中我先对OAuth2.0涉及的一些常用概念进行介绍,然后直接通过一个DEMO来让大家切身感受了OAuth2.0第 ...

随机推荐

  1. Spark: JAVA_HOME is not set

    在Spark项目,sbin目录下的spark-config.sh文件下,最后添加JAVA_HOME的索引. 即可.

  2. print( "Hello,NumPy!" )

    print( "Hello,NumPy!" ) 学习痛苦啊,今天学,明天丢.这种天气,还是睡觉最舒服了. 咱说归说,闹归闹,但还是得学才行啊. 之前在学习的过程中一直都有记录笔记的 ...

  3. MySQL中load data infile将文件中的数据批量导入数据库

    有时候我们需要将文件中的数据直接导入到数据库中,那么我们就可以使用load data infile,下面具体介绍使用方法. dao中的方法 @Autowired private JdbcTemplat ...

  4. NodeJs 加入Windows开机自启动服务

    首先需要到http://nssm.cc/download/?page=download 下载 nssm,下下来之后是压缩包形式的解压之后,在命令行模式下进入到nssm的目录.之后运行:nssm ins ...

  5. Zookeeper(4)---ZK集群部署和选举

    一.集群部署 1.准备三台机器,安装好ZK.强烈建议奇数台机器,因为zookeeper 通过判断大多数节点的存活来判断整个服务是否可用.3个节点,挂掉了2个表示整个集群挂掉,而用偶数4个,挂掉了2个也 ...

  6. Statistical physics approaches to the complex Earth system(相关系统建模理念方法的摘要)

    本文翻译自"Statistical physics approaches to the complex Earth system",其虽然是针对复杂地球系统的统计物理方法的综述,但 ...

  7. prometheus监控golang服务实践

    一.prometheus基本原理介绍 prometheus是基于metric采样的监控,可以自定义监控指标,如:服务每秒请求数.请求失败数.请求执行时间等,每经过一个时间间隔,数据都会从运行的服务中流 ...

  8. Socket 连接错误及原因

    ECONNABORTED   该错误被描述为"software caused connection abort",即"软件引起的连接中止".原因在于当服务和客户 ...

  9. python之 《zip,lambda, map》

    1.zip 对于zip我们一般都是用在矩阵上 eg: a = [1,2,3] b = ['a', 'b', 'c'] x = zip(a, b) print(x) print(list(x)) 结果是 ...

  10. ImportError: No module named 'chardet'

    1.使用requsets出现这个错误,ImportError: No module named 'chardet' 原因:requests依赖其他一些模块 解决:依次使用pip安装即可 pip ins ...