Spring Cloud Security:Oauth2结合JWT使用

Spring Cloud Security 为构建安全的SpringBoot应用提供了一系列解决方案,结合Oauth2还可以实现更多功能,比如使用JWT令牌存储信息,刷新令牌功能,本文将对其结合JWT使用进行详细介绍。

JWT简介

JWT是JSON WEB TOKEN的缩写,它是基于 RFC 7519 标准定义的一种可以安全传输的的JSON对象,由于使用了数字签名,所以是可信任和安全的。

JWT的组成

JWT token的格式:header.payload.signature;

header中用于存放签名的生成算法;

{

"alg": "HS256",

"typ": "JWT"

}Copy to clipboardErrorCopied

payload中用于存放数据,比如过期时间、用户名、用户所拥有的权限等;

{

"exp": 1572682831,

"user_name": "macro",

"authorities": [

  "admin"

],

"jti": "c1a0645a-28b5-4468-b4c7-9623131853af",

"client_id": "admin",

"scope": [

  "all"

]

}Copy to clipboardErrorCopied

signature为以header和payload生成的签名,一旦header和payload被篡改,验证将失败。

JWT实例

这是一个JWT的字符串:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NzI2ODI4MzEsInVzZXJfbmFtZSI6Im1hY3JvIiwiYXV0aG9yaXRpZXMiOlsiYWRtaW4iXSwianRpIjoiYzFhMDY0NWEtMjhiNS00NDY4LWI0YzctOTYyMzEzMTg1M2FmIiwiY2xpZW50X2lkIjoiYWRtaW4iLCJzY29wZSI6WyJhbGwiXX0.x4i6sRN49R6JSjd5hd1Fr2DdEMBsYdC4KB6Uw1huXPgCopy to clipboardErrorCopied

可以在该网站上获得解析结果:https://jwt.io/

创建oauth2-jwt-server模块

该模块只是对oauth2-server模块的扩展,直接复制过来扩展下下即可。

oauth2中存储令牌的方式

在上一节中我们都是把令牌存储在内存中的,这样如果部署多个服务,就会导致无法使用令牌的问题。 Spring Cloud Security中有两种存储令牌的方式可用于解决该问题,一种是使用Redis来存储,另一种是使用JWT来存储。

使用Redis存储令牌

在pom.xml中添加Redis相关依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>Copy to clipboardErrorCopied

在application.yml中添加redis相关配置:

spring:

  redis: #redis相关配置

    password: 123456 #有密码时设置Copy to clipboardErrorCopied

添加在Redis中存储令牌的配置:

/**

* 使用redis存储token的配置

* Created by macro on 2019/10/8.

*/@ConfigurationpublicclassRedisTokenStoreConfig{@AutowiredprivateRedisConnectionFactoryredisConnectionFactory;@BeanpublicTokenStoreredisTokenStore(){returnnewRedisTokenStore(redisConnectionFactory);}}Copy to clipboardErrorCopied

在认证服务器配置中指定令牌的存储策略为Redis:

/**

* 认证服务器配置

* Created by macro on 2019/9/30.

*/@Configuration@EnableAuthorizationServerpublicclassAuthorizationServerConfigextendsAuthorizationServerConfigurerAdapter{@AutowiredprivatePasswordEncoderpasswordEncoder;@AutowiredprivateAuthenticationManagerauthenticationManager;@AutowiredprivateUserServiceuserService;@Autowired@Qualifier("redisTokenStore")privateTokenStoretokenStore;/**

    * 使用密码模式需要配置

    */@Overridepublicvoidconfigure(AuthorizationServerEndpointsConfigurerendpoints){endpoints.authenticationManager(authenticationManager).userDetailsService(userService).tokenStore(tokenStore);//配置令牌存储策略}//省略代码...}Copy to clipboardErrorCopied

运行项目后使用密码模式来获取令牌,访问如下地址:http://localhost:9401/oauth/token

进行获取令牌操作,可以发现令牌已经被存储到Redis中。

使用JWT存储令牌

添加使用JWT存储令牌的配置:

/**

* 使用Jwt存储token的配置

* Created by macro on 2019/10/8.

*/@ConfigurationpublicclassJwtTokenStoreConfig{@BeanpublicTokenStorejwtTokenStore(){returnnewJwtTokenStore(jwtAccessTokenConverter());}@BeanpublicJwtAccessTokenConverterjwtAccessTokenConverter(){JwtAccessTokenConverteraccessTokenConverter=newJwtAccessTokenConverter();accessTokenConverter.setSigningKey("test_key");//配置JWT使用的秘钥returnaccessTokenConverter;}}Copy to clipboardErrorCopied

在认证服务器配置中指定令牌的存储策略为JWT:

/**

* 认证服务器配置

* Created by macro on 2019/9/30.

*/@Configuration@EnableAuthorizationServerpublicclassAuthorizationServerConfigextendsAuthorizationServerConfigurerAdapter{@AutowiredprivatePasswordEncoderpasswordEncoder;@AutowiredprivateAuthenticationManagerauthenticationManager;@AutowiredprivateUserServiceuserService;@Autowired@Qualifier("jwtTokenStore")privateTokenStoretokenStore;@AutowiredprivateJwtAccessTokenConverterjwtAccessTokenConverter;@AutowiredprivateJwtTokenEnhancerjwtTokenEnhancer;/**

    * 使用密码模式需要配置

    */@Overridepublicvoidconfigure(AuthorizationServerEndpointsConfigurerendpoints){endpoints.authenticationManager(authenticationManager).userDetailsService(userService).tokenStore(tokenStore)//配置令牌存储策略.accessTokenConverter(jwtAccessTokenConverter);}//省略代码...}Copy to clipboardErrorCopied

运行项目后使用密码模式来获取令牌,访问如下地址:http://localhost:9401/oauth/token

发现获取到的令牌已经变成了JWT令牌,将access_token拿到https://jwt.io/ 网站上去解析下可以获得其中内容。

{

  "exp": 1572682831,

  "user_name": "macro",

  "authorities": [

    "admin"

  ],

  "jti": "c1a0645a-28b5-4468-b4c7-9623131853af",

  "client_id": "admin",

  "scope": [

    "all"

  ]

}Copy to clipboardErrorCopied

扩展JWT中存储的内容

有时候我们需要扩展JWT中存储的内容,这里我们在JWT中扩展一个key为enhance,value为enhance info的数据。

继承TokenEnhancer实现一个JWT内容增强器:

/**

* Jwt内容增强器

* Created by macro on 2019/10/8.

*/publicclassJwtTokenEnhancerimplementsTokenEnhancer{@OverridepublicOAuth2AccessTokenenhance(OAuth2AccessTokenaccessToken,OAuth2Authenticationauthentication){Map<String,Object>info=newHashMap<>();info.put("enhance","enhance info");((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(info);returnaccessToken;}}Copy to clipboardErrorCopied

创建一个JwtTokenEnhancer实例:

/**

* 使用Jwt存储token的配置

* Created by macro on 2019/10/8.

*/@ConfigurationpublicclassJwtTokenStoreConfig{//省略代码...@BeanpublicJwtTokenEnhancerjwtTokenEnhancer(){returnnewJwtTokenEnhancer();}}Copy to clipboardErrorCopied

在认证服务器配置中配置JWT的内容增强器:

/**

* 认证服务器配置

* Created by macro on 2019/9/30.

*/@Configuration@EnableAuthorizationServerpublicclassAuthorizationServerConfigextendsAuthorizationServerConfigurerAdapter{@AutowiredprivatePasswordEncoderpasswordEncoder;@AutowiredprivateAuthenticationManagerauthenticationManager;@AutowiredprivateUserServiceuserService;@Autowired@Qualifier("jwtTokenStore")privateTokenStoretokenStore;@AutowiredprivateJwtAccessTokenConverterjwtAccessTokenConverter;@AutowiredprivateJwtTokenEnhancerjwtTokenEnhancer;/**

    * 使用密码模式需要配置

    */@Overridepublicvoidconfigure(AuthorizationServerEndpointsConfigurerendpoints){TokenEnhancerChainenhancerChain=newTokenEnhancerChain();List<TokenEnhancer>delegates=newArrayList<>();delegates.add(jwtTokenEnhancer);//配置JWT的内容增强器delegates.add(jwtAccessTokenConverter);enhancerChain.setTokenEnhancers(delegates);endpoints.authenticationManager(authenticationManager).userDetailsService(userService).tokenStore(tokenStore)//配置令牌存储策略.accessTokenConverter(jwtAccessTokenConverter).tokenEnhancer(enhancerChain);}//省略代码...}Copy to clipboardErrorCopied

运行项目后使用密码模式来获取令牌,之后对令牌进行解析,发现已经包含扩展的内容。

{

  "user_name": "macro",

  "scope": [

    "all"

  ],

  "exp": 1572683821,

  "authorities": [

    "admin"

  ],

  "jti": "1ed1b0d8-f4ea-45a7-8375-211001a51a9e",

  "client_id": "admin",

  "enhance": "enhance info"

}Copy to clipboardErrorCopied

Java中解析JWT中的内容

如果我们需要获取JWT中的信息,可以使用一个叫jjwt的工具包。

在pom.xml中添加相关依赖:

<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.0</version></dependency>Copy to clipboardErrorCopied

修改UserController类,使用jjwt工具类来解析Authorization头中存储的JWT内容。

/**

* Created by macro on 2019/9/30.

*/@RestController@RequestMapping("/user")publicclassUserController{@GetMapping("/getCurrentUser")publicObjectgetCurrentUser(Authenticationauthentication,HttpServletRequestrequest){Stringheader=request.getHeader("Authorization");Stringtoken=StrUtil.subAfter(header,"bearer ",false);returnJwts.parser().setSigningKey("test_key".getBytes(StandardCharsets.UTF_8)).parseClaimsJws(token).getBody();}}Copy to clipboardErrorCopied

将令牌放入Authorization头中,访问如下地址获取信息:http://localhost:9401/user/getCurrentUser

刷新令牌

在Spring Cloud Security 中使用oauth2时,如果令牌失效了,可以使用刷新令牌通过refresh_token的授权模式再次获取access_token。

只需修改认证服务器的配置,添加refresh_token的授权模式即可。

/**

* 认证服务器配置

* Created by macro on 2019/9/30.

*/@Configuration@EnableAuthorizationServerpublicclassAuthorizationServerConfigextendsAuthorizationServerConfigurerAdapter{@Overridepublicvoidconfigure(ClientDetailsServiceConfigurerclients)throwsException{clients.inMemory().withClient("admin").secret(passwordEncoder.encode("admin123456")).accessTokenValiditySeconds(3600).refreshTokenValiditySeconds(864000).redirectUris("http://www.baidu.com").autoApprove(true)//自动授权配置.scopes("all").authorizedGrantTypes("authorization_code","password","refresh_token");//添加授权模式}}Copy to clipboardErrorCopied

使用刷新令牌模式来获取新的令牌,访问如下地址:http://localhost:9401/oauth/token

使用到的模块

springcloud-learning

└── oauth2-jwt-server -- 使用jwt的oauth2认证测试服务

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容