关于 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. P1948 [USACO08JAN]Telephone Lines S

    题意描述 在无向图中求一条从 \(1\) 到 \(N\) 的路径,使得路径上第 \(K+1\) 大的边权最小. 等等,最大的最小...如此熟悉的字眼,难道是 二分答案. 下面进入正题. 算法分析 没错 ...

  2. hadoop使用实例

    一.词频统计 1.下载喜欢的电子书或大量文本数据,并保存在本地文本文件中 2.编写map与reduce函数 3.本地测试map与reduce 4.将文本数据上传至HDFS上 5.用hadoop str ...

  3. Spring AOP实现注解式的Mybatis多数据源切换

    一.为什么要使用多数据源切换? 多数据源切换是为了满足什么业务场景?正常情况下,一个微服务或者说一个WEB项目,在使用Mybatis作为数据库链接和操作框架的情况下通常只需要构建一个系统库,在该系统库 ...

  4. leetcode45:maximum depth of binary tree

    题目描述 求给定二叉树的最大深度, 最大深度是指树的根结点到最远叶子结点的最长路径上结点的数量. Given a binary tree, find its maximum depth. The ma ...

  5. 炸了!一口气问了我18个JVM问题!

    前言 GC 对于Java 来说重要性不言而喻,不论是平日里对 JVM 的调优还是面试中的无情轰炸. 这篇文章我会以一问一答的方式来展开有关 GC 的内容. 不过在此之前强烈建议先看这篇文章深度揭秘垃圾 ...

  6. Collection迭代器Iterator的使用

    package com.cx.Collecion; import java.util.ArrayList; import java.util.Collection; import java.util. ...

  7. Java iText+FreeMarker生成PDF(HTML转PDF)

    1.背景 在某些业务场景中,需要提供相关的电子凭证,比如网银/支付宝中转账的电子回单,签约的电子合同等.方便用户查看,下载,打印.目前常用的解决方案是,把相关数据信息,生成对应的pdf文件返回给用户. ...

  8. JavaScript兼容性总结一点点

    JavaScript 不同浏览器之间的差异还是很大,所以js库才这么有需求,需要解决各种兼容性问题. 其实反过来,既然存在js库能解决这些兼容性问题,说明底层大部分功能还是相通的. 首先想到的是事件模 ...

  9. UI自动化中无头浏览器的应用

    因为某次工作中写了个脚本要来回跑,还要在本机上做很多其他的事情,所以就上网找了个方法,无头浏览器,这样就不会浏览器来回弹出来,执行用例还会很快. 废话不多说,直接放代码: #coding=utf-8 ...

  10. Ceph 状态报警告 pool rbd has many more objects per pg than average (too few pgs?)

    定位问题 [root@lab8106 ~]# ceph -s cluster fa7ec1a1-662a-4ba3-b478-7cb570482b62 health HEALTH_WARN pool ...