使用JWT作为Spring Security OAuth2的token存储问题
序
spring security oauth2的demo在前几篇文章中已经讲过了,在那些模式中使用的都是remotetokenservice调用授权服务器来校验token,返回校验通过的用户信息供上下文中获取
这种方式会加重授权服务器的负载,你想啊,当用户没授权时候获取token得找授权服务器,有token了访问资源服务器还要访问授权服务器,相当于说每次请求都要访问授权服务器,这样对授权服务器的负载会很大
常规的方式有两种来解决这个问题:
- 使用jwt作为token传递
- 使用redis存储token,资源服务器本地访问redis校验token
使用jwt与redis都可以在资源服务器中进行校验token,从而减少授权服务器的工作量
jwt默认使用hmacsha256对称加密算法,以下记录下默认算法实现与非对称rsa算法的集成,使用不同算法加解密测试方法是一致的,所以放在文章最后
授权服务器整合jwt——对称加解密算法
授权服务器整体代码结构
pom.xml中引入依赖
<dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-security</artifactid> <version>2.2.1.release</version> </dependency> <!-- spring security oauth2 --> <dependency> <groupid>org.springframework.security.oauth</groupid> <artifactid>spring-security-oauth2</artifactid> <version>2.4.0.release</version> </dependency> <dependency> <groupid>org.springframework.security</groupid> <artifactid>spring-security-jwt</artifactid> <version>1.1.0.release</version> </dependency>
securityconfig配置,主要需要显式声明authenticationmanager和userdetailsservice这两个bean
@configuration @enablewebsecurity public class securityconfig extends websecurityconfigureradapter { @bean public authenticationmanager authenticationmanager() throws exception { return super.authenticationmanager(); } @bean public userdetailsservice userdetailsservice(){ //主要是配置这个bean,用于授权服务器配置中注入 return super.userdetailsservice(); } @bean public passwordencoder passwordencoder(){ return new bcryptpasswordencoder(); } @override protected void configure(authenticationmanagerbuilder auth) throws exception { // @formatter: off auth.inmemoryauthentication() .withuser("hellxz") .password(passwordencoder().encode("xyz")) .authorities(collections.emptylist()); // @formatter: on } @override protected void configure(httpsecurity http) throws exception { http.authorizerequests() .anyrequest().authenticated() //所有请求都需要通过认证 .and() .httpbasic() //basic提交 .and() .csrf().disable(); //关跨域保护 } }
授权服务器配置authorizationconfig
@configuration @enableauthorizationserver //开启授权服务 public class authorizationconfig extends authorizationserverconfigureradapter { @autowired private authenticationmanager authenticationmanager; @autowired public userdetailsservice userdetailsservice; @autowired private passwordencoder passwordencoder; @override public void configure(authorizationserversecurityconfigurer security) throws exception { //允许表单提交 security.allowformauthenticationforclients() .checktokenaccess("permitall()") .tokenkeyaccess("permitall()"); } @override public void configure(clientdetailsserviceconfigurer clients) throws exception { // @formatter: off clients.inmemory() .withclient("client-a") //client端唯一标识 .secret(passwordencoder.encode("client-a-secret")) //client-a的密码,这里的密码应该是加密后的 .authorizedgranttypes("authorization_code", "password", "refresh_token") //授权模式标识,这里主要测试用password模式,另外refresh_token不是一种模式,但是可以使用它来刷新access_token(在它的有效期内) .scopes("read_user_info") //作用域 .resourceids("resource1") //资源id,如不需限制资源id,注释此处即可 .redirecturis("http://localhost:9001/callback"); //回调地址 // @formatter: on } @override public void configure(authorizationserverendpointsconfigurer endpoints) throws exception { endpoints.authenticationmanager(authenticationmanager) .userdetailsservice(userdetailsservice) .tokenstore(jwttokenstore()) //设置jwttoken为tokenstore .accesstokenconverter(jwtaccesstokenconverter());//设置access_token转换器 } /** * jwt访问token转换器 */ @bean public jwtaccesstokenconverter jwtaccesstokenconverter(){ jwtaccesstokenconverter converter = new jwtaccesstokenconverter(); converter.setsigningkey("my-sign-key"); //资源服务器需要配置此选项方能解密jwt的token return converter; } /** * jwt的token存储对象 */ @bean public jwttokenstore jwttokenstore(){ return new jwttokenstore(jwtaccesstokenconverter()); } }
这里主要是在configure(authorizationserverendpointsconfigurer endpoints)
授权服务的端点配置中加入jwt的tokenstore和access_token的转换器,以及这二者的声明bean方法
这里使用的是默认对称mac算法,即加密解密使用相同的密钥
启动类就不说了,开启@springbootapplicatin的main方法
资源服务器整合jwt——对称加解密算法
资源服务器主要就一个资源配置类
@configuration @enableresourceserver public class resourceconfig extends resourceserverconfigureradapter { @bean public passwordencoder passwordencoder() { return new bcryptpasswordencoder(); } @override public void configure(httpsecurity http) throws exception { //设置创建session策略 http.sessionmanagement().sessioncreationpolicy(sessioncreationpolicy.if_required); //@formatter:off //所有请求必须授权 http.authorizerequests() .anyrequest().authenticated(); //@formatter:on } @override public void configure(resourceserversecurityconfigurer resources) { //@formatter:off //如不需要限制资源id,请在授权配置处去除resourceids的配置 resources.resourceid("resource1") .tokenstore(jwttokenstore()); //@formatter:on } /** * jwt访问token转换器 */ @bean public jwtaccesstokenconverter jwtaccesstokenconverter(){ jwtaccesstokenconverter converter = new jwtaccesstokenconverter(); converter.setsigningkey("my-sign-key"); //与授权服务器相同的signingkey return converter; } /** * jwt的token存储对象 */ @bean public jwttokenstore jwttokenstore(){ return new jwttokenstore(jwtaccesstokenconverter()); } }
配置jwt的tokenstore和accesstokenconverter与授权服器相同,添加启动类完成配置
oauth整合jwt——非对称加解密rsa
本部分基于对称加密部分,仅展示需要修改的部分
首先使用keytool生成jks (java key store) 密钥,按提示输入姓氏等信息
keytool -genkeypair -alias hellxz-jwt -validity 3650 -keyalg rsa -keypass hellxztest -keystore hellxz-jwt.jks -storepass hellxztest
生成的私钥文件会在当前目录,把hellxz-jwt.jks复制到授权服务器的resources目录下
授权服务器需修改jwtaccesstokenconverter()
@bean public jwtaccesstokenconverter jwtaccesstokenconverter(){ jwtaccesstokenconverter converter = new jwtaccesstokenconverter(); keystorekeyfactory storekeyfactory = new keystorekeyfactory( new classpathresource("hellxz-jwt.jks"), "hellxztest".tochararray()); converter.setkeypair(storekeyfactory.getkeypair("hellxz-jwt")); return converter; }
在hellxz-jwt.jks同目录下,执行命令生成公钥
➜ keytool -list -rfc --keystore hellxz-jwt.jks | openssl x509 -inform pem -pubkey
输入密钥库口令: hellxztest
-----begin public key-----
miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqeaxu7zulfuvbxmzd28xwm4
ul5e9yfrtolgwkhlnllp904/gbiwboz4tcbcnq3vxlgbn9voqfp1p5c7frgz95ui
7shkckgsffgl2raqsplmdcln/adfsxmpf06rvikggce9tr0q0ioncan+b/lark4t
au76qsqwn9mlxlznvfczclzozsfdnju+1jubzqt6fepwqalbuvydv0zcudg8ikn1
l9d0m1tssakpitru2yeuguji+79ury7y8bclex6d4ctl9tqahl5g32gojec0s2y+
0bqequsv1nut9kijt9kiova+q7o2t8ohuqqt9le7kvmii4gsx5vsnvvzage2uglh
zqidaqab
-----end public key-----
-----begin certificate-----
miidutccajmgawibagieepedczanbgkqhkig9w0baqsfadbzmqswcqydvqqgewjd
tjeqma4ga1uecbmhymvpamluzzeqma4ga1uebxmhymvpamluzzekmagga1uechmb
mdekmagga1uecxmbmdeomawga1ueaxmfemhhbmcwhhcnmtkxmje1mduyotm2whcn
mjkxmjeymduyotm2wjbzmqswcqydvqqgewjdtjeqma4ga1uecbmhymvpamluzzeq
ma4ga1uebxmhymvpamluzzekmagga1uechmbmdekmagga1uecxmbmdeomawga1ue
axmfemhhbmcwggeima0gcsqgsib3dqebaquaa4ibdwawggekaoibaqdftvo6uvru
fezkpbzhazi6xl73iwtogubyoeu0uwn3tj8zujyghni1wfw2rdxesye31u6p8/u/
klt9gdp3lqjtkeoiqcwuuyvascqymuwmku39p1+zgakxtqtuiqabx721hrdsi41x
o35v+ucsrhmc7vpcxdcf0wtexodv9znyvk5lj8m2o77um4hoq3p8q9apqufrvh1x
tmjqmbykq3wx0psbw1jjoqmjottbirqzsol7v1svltjwekurfp3gjox1nacevmdf
yagkrzrlbl7rup6psy/wds30qilp2si68d5dujzpw4e6pbp2v7us+yilibjfm9i2
+9lqatzscwhnagmbaagjitafmb0ga1uddgqwbbqf96rk7n0xufnvtjuh9td9ixza
6zanbgkqhkig9w0baqsfaaocaqeaumzwzjhej6+4tggodqkq5l5rbtoubesxa1ue
s9ia4m/jnznvcxje0ny47yvzbcikisyalswgoomj1pijxempggxvmiuijpapgg+4
sthzisxkzx0ru8irjtapaglmi74ai6s73ltbske9gepgwwnbtduzousisnt1oj0j
ehfhdpuzxc36nedfrbobxw4w3qhstlktn2wjm1nlv96nfkmqjhqjhhkt6ihe7hmg
qwxznswaqv9gjndkzt5teqwnkt6h7r1nx5ojkj0kn1dzy0o3rddd5e0kdkkmtwoh
3dejh6uvtt/dw/drzjlbyndepp6hygqu2dw5jg5uihuzfhnjea==
-----end certificate-----
复制公钥部分到public.cert放到资源服务器的resources目录
-----begin public key-----
miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqeaxu7zulfuvbxmzd28xwm4
ul5e9yfrtolgwkhlnllp904/gbiwboz4tcbcnq3vxlgbn9voqfp1p5c7frgz95ui
7shkckgsffgl2raqsplmdcln/adfsxmpf06rvikggce9tr0q0ioncan+b/lark4t
au76qsqwn9mlxlznvfczclzozsfdnju+1jubzqt6fepwqalbuvydv0zcudg8ikn1
l9d0m1tssakpitru2yeuguji+79ury7y8bclex6d4ctl9tqahl5g32gojec0s2y+
0bqequsv1nut9kijt9kiova+q7o2t8ohuqqt9le7kvmii4gsx5vsnvvzage2uglh
zqidaqab
-----end public key-----
修改资源服务器jwtaccesstokenconverter()方法
@bean public jwtaccesstokenconverter jwtaccesstokenconverter(){ jwtaccesstokenconverter converter = new jwtaccesstokenconverter(); resource resource = new classpathresource("public.cert"); string publickey; try { publickey = new string(filecopyutils.copytobytearray(resource.getinputstream())); } catch (ioexception e) { throw new runtimeexception(e); } converter.setverifierkey(publickey); return converter; }
测试验证
发送post请求http://localhost:8080/oauth/token?username=hellxz&password=xyz&scope=read_user_info&grant_type=password
返回结果
带token访问资源服务器
测试通过
另外使用jwt应设置尽量短的过期时间,因为jwt的token无法手动revoke,只能等待其到达过期时间失效
到此这篇关于使用jwt作为spring security oauth2的token存储的文章就介绍到这了,更多相关spring security oauth2 token存储内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: Perl5 OOP学习笔记第1/2页
下一篇: 直播带货,告别网红时代