阅读此文,希望是对JWT以及OAuth2有一定了解的童鞋。

JWT认证,提供了对称加密以及非对称的实现。

内容源码点我

涉及到源码中两个服务

spring-boot-oauth-jwt-server

spring-boot-oauth-jwt-resource-server


认证服务端

提供认证、授权服务

实现方式,主要复写AuthorizationServerConfigurerAdapter实现

认证服务1-对称加密方式

对称加密,表示认证服务端和认证客户端的共用一个密钥

实现方式

  • AccessToken转换器-定义token的生成方式,这里使用JWT生成token,对称加密只需要加入key等其他信息(自定义)。
          @Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
return converter;
}
  • 告诉spring security token的生成方式
        @Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore())
.accessTokenConverter(accessTokenConverter())
.authenticationManager(authenticationManager);
}

以上对称加密的JWT方式的认证服务端就OK了,后面有对应的资源服务端的内容。

认证服务2-非对称加密方式(公钥密钥)

服务端生成公钥和密钥,每个客户端使用获取到的公钥到服务器做认证。

因此首先要生成一个证书,导出公钥再后续步骤

实现方式

  • 生成JKS文件

      keytool -genkeypair -alias mytest -keyalg RSA -keypass mypass -keystore mytest.jks -storepass mypass
jks

具体参数的意思不另说明。

  • 导出公钥

      keytool -list -rfc --keystore mytest.jks | openssl x509 -inform pem -pubkey
publicKey
  • 生成公钥文本

      -----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhAF1qpL+8On3rF2M77lR
    +l3WXKpGXIc2SwIXHwQvml/4SG7fJcupYVOkiaXj4f8g1e7qQCU4VJGvC/gGJ7sW
    fn+L+QKVaRhs9HuLsTzHcTVl2h5BeawzZoOi+bzQncLclhoMYXQJJ5fULnadRbKN
    HO7WyvrvYCANhCmdDKsDMDKxHTV9ViCIDpbyvdtjgT1fYLu66xZhubSHPowXXO15
    LGDkROF0onqc8j4V29qy5iSnx8I9UIMEgrRpd6raJftlAeLXFa7BYlE2hf7cL+oG
    hY+q4S8CjHRuiDfebKFC1FJA3v3G9p9K4slrHlovxoVfe6QdduD8repoH07jWULu
    qQIDAQAB
    -----END PUBLIC KEY-----
    >

存储为public.txt。把 mytest.jks和public.txt放入resource目录下

  • 这里我们要修改JwtAccessTokenConverter,把证书导入
        @Bean
public TokenEnhancer accessTokenConverter() {
final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
KeyStoreKeyFactory keyStoreKeyFactory =
new KeyStoreKeyFactory(new ClassPathResource("mytest.jks"), "mypass".toCharArray());
converter.setKeyPair(keyStoreKeyFactory.getKeyPair("mytest"));
        converter<span class="token punctuation">.</span><span class="token function">setAccessTokenConverter</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">CustomerAccessTokenConverter</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">return</span> converter<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

以上,就可以实现非对称加密了

额外信息(这部分信息不关乎加密方式)

  • 自定义生成token携带的信息

有时候需要额外的信息加到token返回中,这部分也可以自定义,此时我们可以自定义一个TokenEnhancer

TokenEnhancer 接口提供一个 enhance(OAuth2AccessToken var1, OAuth2Authentication var2) 方法,用于对token信息的添加,信息来源于 OAuth2Authentication

这里我们加入了用户的授权信息。

            @Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
final Map<String, Object> additionalInfo = new HashMap<>();
User user = (User) authentication.getUserAuthentication().getPrincipal();
additionalInfo.put("username", user.getUsername());
additionalInfo.put("authorities", user.getAuthorities());
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
}

同样要告诉spring security,我们把这个TokenEnhancer加入到TokenEnhancer链中(链,所以可以好多个)

        // 自定义token生成方式
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
tokenEnhancerChain.setTokenEnhancers(Arrays.asList(customerEnhancer(), accessTokenConverter()));
endpoints.tokenEnhancer(tokenEnhancerChain);
  • 自定义token信息中添加的信息

JWT中,需要在token中携带额外的信息,这样可以在服务之间共享部分用户信息,spring security默认在JWT的token中加入了user_name,如果我们需要额外的信息,需要自定义这部分内容。

JwtAccessTokenConverter是我们用来生成token的转换器,所以我们需要配置这里面的部分信息来达到我们的目的。

JwtAccessTokenConverter默认使用DefaultAccessTokenConverter来处理token的生成、装换、获取。DefaultAccessTokenConverter中使用UserAuthenticationConverter来对应处理token与userinfo的获取、转换。因此我们需要重写下UserAuthenticationConverter对应的转换方法就可以

        @Override
public Map<String, ?> convertUserAuthentication(Authentication authentication) {
LinkedHashMap response = new LinkedHashMap();
response.put("user_name", authentication.getName());
response.put("name", ((User) authentication.getPrincipal()).getName());
response.put("id", ((User) authentication.getPrincipal()).getId());
response.put("createAt", ((User) authentication.getPrincipal()).getCreateAt());
if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
response.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
}
        <span class="token keyword">return</span> response<span class="token punctuation">;</span>
<span class="token punctuation">}</span>

告诉JwtAccessTokenConverter ,把我们的方式替换默认的方式

        @Bean
public TokenEnhancer accessTokenConverter() {
final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey("123");
converter.setAccessTokenConverter(new CustomerAccessTokenConverter());
return converter;
}

资源服务端

实现方式,主要复写ResourceServerConfigurerAdapter实现

资源服务1-对称加密方式

此处配置与认证服务基本一致,不同的是,资源服务器配置是在ResourceServerConfigurerAdapter做配置,其他的看源码吧,大差不差。

资源服务2-非对称加密方式(公钥)

把 public.txt放入resource目录下

修改JwtAccessTokenConverter如下:

        @Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
Resource resource = new ClassPathResource("public.txt");
String publicKey = null;
try {
publicKey = inputStream2String(resource.getInputStream());
} catch (final IOException e) {
throw new RuntimeException(e);
}
converter.setVerifierKey(publicKey);
converter.setAccessTokenConverter(new CustomerAccessTokenConverter());
return converter;
}

然后就可以跑起来了。

效果验证

token获取

code获取:

http://127.0.0.1:8081/oauth/authorize?client_id=clientId&response_type=code&redirect_uri=http://127.0.0.1:8082/login/my

redirect_uri:需要与配置在认证服务器中的一致。

client_id:client_id也是预先在认证服务器中,这里是保存在数据库里的

response_type:写死code

浏览器进入后的页面。

密码验证

输入账号密码,这个也是保存在数据库,默认是保存在内存中。

授权之后就可以获得code

http://127.0.0.1:8082/login/my?code=rTKETX

根据这个code,POST下获取token

http://127.0.0.1:8081/oauth/token?grant_type=authorization_code&code=rTKETX&redirect_uri=http://127.0.0.1:8082/login/my&client_id=clientId&client_secret=secret
token获取请求

grant_type:这里写死authorization_code

code:上面得到的rTKETX

redirect_uri:同上不变

client_id:同上不变

client_secret:对应的密码

结果返回如下:

token获取内容

token验证

http://127.0.0.1:8081/oauth/check_token?token=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...

验证token

用户信息获取

用户信息

资源服务端就不展示了...

原文地址:https://www.jianshu.com/p/2c231c96a29b

Spring Boot,Spring Security实现OAuth2 + JWT认证的更多相关文章

  1. Spring Boot+Spring Security+JWT 实现 RESTful Api 认证(二)

    Spring Boot+Spring Security+JWT 实现 RESTful Api 认证(二) 摘要 上一篇https://javaymw.com/post/59我们已经实现了基本的登录和t ...

  2. Spring Boot+Spring Security+JWT 实现 RESTful Api 认证(一)

    标题 Spring Boot+Spring Security+JWT 实现 RESTful Api 认证(一) 技术 Spring Boot 2.Spring Security 5.JWT 运行环境 ...

  3. 基于Spring Boot+Spring Security+JWT+Vue前后端分离的开源项目

    一.前言 最近整合Spring Boot+Spring Security+JWT+Vue 完成了一套前后端分离的基础项目,这里把它开源出来分享给有需要的小伙伴们 功能很简单,单点登录,前后端动态权限配 ...

  4. Spring boot +Spring Security + Thymeleaf 认证失败返回错误信息

    [Please make sure to select the branch corresponding to the version of Thymeleaf you are using] Stat ...

  5. [权限管理系统(四)]-spring boot +spring security短信认证+redis整合

    [权限管理系统]spring boot +spring security短信认证+redis整合   现在主流的登录方式主要有 3 种:账号密码登录.短信验证码登录和第三方授权登录,前面一节Sprin ...

  6. 255.Spring Boot+Spring Security:使用md5加密

    说明 (1)JDK版本:1.8 (2)Spring Boot 2.0.6 (3)Spring Security 5.0.9 (4)Spring Data JPA 2.0.11.RELEASE (5)h ...

  7. 256.Spring Boot+Spring Security: MD5是加密算法吗?

    说明 (1)JDK版本:1.8 (2)Spring Boot 2.0.6 (3)Spring Security 5.0.9 (4)Spring Data JPA 2.0.11.RELEASE (5)h ...

  8. Spring Boot+Spring Security:获取用户信息和session并发控制

    说明 (1)JDK版本:1.8(2)Spring Boot 2.0.6(3)Spring Security 5.0.9(4)Spring Data JPA 2.0.11.RELEASE(5)hiber ...

  9. 快速搭建基于Spring Boot + Spring Security 环境

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 1.Spring Security 权限管理框架介绍 简介: Spring Security 提供了基于 ...

随机推荐

  1. 《RabbitMQ 实战》读书笔记

    MQ的好处: 1.业务上接口(系统扩展性变强) 2.性能提升(同步变异步,效率提高,还方便做负载均衡) 3.技术兼容(可以连接各种不同语言的系统,作为粘合剂) 读书笔记: 1.消息队列的应用场景:系统 ...

  2. coci2011 debt 还债

    coci2011 debt 还债 Description 有N个人,每个人恰好欠另一个人Bi元钱,现在大家都没有钱,政府想要给其中一些人欠,使得大家都不欠别人钱. 如A欠B 50,B欠C 20,则当政 ...

  3. java.lang.Thread类的静态方法sleep()和yield()的比较

    [线程让步yield()方法] yield()方法可以让当前正在执行的线程暂停,但它不会阻塞该线程,它只是将该线程从运行状态转入就绪状态. 只是让当前的线程暂停一下,让系统的线程调度器重新调度一次. ...

  4. IOC注解方式1.0

    在spring4之后,想要使用注解形式,必须得要引入aop的包 在配置文件当中,还得要引入一个context约束 <?xml version="1.0" encoding=& ...

  5. max函数比较字符串类型

    关于sql中 max函数比较字符串类型 max只比较首个字符的大小 只要首字母大,则不比较其他位置的字母,若首字母相同,则比较顺序位字母. 今天死在这了 数据库中 step字段类型char分别为 5. ...

  6. Mac 上ssh远程连接Linux服务器提示Host key verification failed.

    当我们对重装远程服务器的时候会出现Host key verification failed问题 解决办法: rm -rf ~/.ssh/known_hosts 重新ssh连接,OK!

  7. 根据 sitemap 的规则[0],当前页面 [pages/index/index] 将被索引

    sitemap 的索引提示是默认开启的,如需要关闭 sitemap 的索引提示,可在小程序项目配置文件 project.config.json 的 setting 中配置字段 checkSiteMap ...

  8. iOS - 点击UIButton不变灰,button的image不变灰

    要想让uibutton点击不变灰 初始化的时候就不能 UIButton *button = [[UIButton alloc]init]; 初始化的时候酱紫,可以保证button点击时不变灰 UIBu ...

  9. 【翻译】Flink Table Api & SQL —Streaming 概念 ——时间属性

    本文翻译自官网: Time Attributes   https://ci.apache.org/projects/flink/flink-docs-release-1.9/dev/table/str ...

  10. JAVA Asponse.Word Office 操作神器,借助 word 模板生成 word 文档,并转化为 pdf,png 等多种格式的文件

    一,由于该 jar 包不是免费的, maven 仓库一般不会有,需要我们去官网下载并安装到本地 maven 仓库 1,用地址   https://www-evget-com/product/564  ...