Spring Cloud入门-Oauth2授权之JWT集成(Hoxton版本)

@Configuration

@EnableAuthorizationServer

public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired

private PasswordEncoder passwordEncoder;

@Autowired

private AuthenticationManager authenticationManager;

@Autowired

private UserService userService;

@Autowired

@Qualifier(“redisTokenStore”)

private TokenStore tokenStore;

/**

  • 使用密码模式需要配置

*/

@Override

public void configure(AuthorizationServerEndpointsConfigurer endpoints) {

endpoints.authenticationManager(authenticationManager)

.userDetailsService(userService)

//配置令牌存储策略

.tokenStore(tokenStore);

}

//省略代码…

}

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

在这里插入图片描述

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

在这里插入图片描述

使用JWT存储令牌

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

@Configuration

public class JwtTokenStoreConfig {

@Bean

@Primary

public TokenStore jwtTokenStore() {

return new JwtTokenStore(jwtAccessTokenConverter());

}

@Bean

public JwtTokenEnhancer jwtTokenEnhancer() {

return new JwtTokenEnhancer();

}

@Bean

public JwtAccessTokenConverter jwtAccessTokenConverter() {

JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();

// 配置jwt使用的密钥

jwtAccessTokenConverter.setSigningKey(“test_key”);

return jwtAccessTokenConverter;

}

}

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

@Configuration

@EnableAuthorizationServer

public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired

private PasswordEncoder passwordEncoder;

@Autowired

private AuthenticationManager authenticationManager;

@Autowired

private UserService userService;

@Autowired

@Qualifier(“jwtTokenStore”)

private TokenStore tokenStore;

@Autowired

private JwtAccessTokenConverter jwtAccessTokenConverter;

@Autowired

private JwtTokenEnhancer jwtTokenEnhancer;

/**

  • 使用密码模式需要配置

*/

@Override

public void configure(AuthorizationServerEndpointsConfigurer endpoints) {

endpoints.authenticationManager(authenticationManager)

.userDetailsService(userService)

//配置令牌存储策略

.tokenStore(tokenStore)

.accessTokenConverter(jwtAccessTokenConverter);

}

//省略代码…

}

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

在这里插入图片描述

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

{

“exp”: 1577678092,

“user_name”: “jourwon”,

“authorities”: [

“admin”

],

“jti”: “87db4bdf-2936-420d-87b9-fb580e255a4d”,

“client_id”: “admin”,

“scope”: [

“all”

]

}

扩展JWT中存储的内容


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

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

public class JwtTokenEnhancer implements TokenEnhancer {

@Override

public OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {

Map<String, Object> info = new HashMap<>();

info.put(“enhance”, “enhance info”);

((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(info);

return oAuth2AccessToken;

}

}

创建一个JwtTokenEnhancer实例:

@Configuration

public class JwtTokenStoreConfig {

//省略代码…

@Bean

public JwtTokenEnhancer jwtTokenEnhancer() {

return new JwtTokenEnhancer();

}

}

在授权服务器配置中配置JWT的内容增强器:

@Configuration

@EnableAuthorizationServer

public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Autowired

private PasswordEncoder passwordEncoder;

@Autowired

private AuthenticationManager authenticationManager;

@Autowired

private UserService userService;

@Autowired

@Qualifier(“jwtTokenStore”)

private TokenStore tokenStore;

@Autowired

private JwtAccessTokenConverter jwtAccessTokenConverter;

@Autowired

private JwtTokenEnhancer jwtTokenEnhancer;

/**

  • 使用密码模式需要配置

  • @param endpoints

  • @throws Exception

*/

@Override

public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {

TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();

List delegates = new ArrayList<>();

// 配置jwt内容增强器

delegates.add(jwtTokenEnhancer);

delegates.add(jwtAccessTokenConverter);

tokenEnhancerChain.setTokenEnhancers(delegates);

endpoints.authenticationManager(authenticationManager)

.userDetailsService(userService)

// 配置令牌存储策略

.tokenStore(tokenStore)

.accessTokenConverter(jwtAccessTokenConverter)

.tokenEnhancer(tokenEnhancerChain);

}

// 省略代码…

}

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

{

“user_name”: “jourwon”,

“scope”: [

“all”

],

“exp”: 1577678449,

“authorities”: [

“admin”

],

“jti”: “618cda6a-dfce-4966-b0df-00607f693ab5”,

“client_id”: “admin”,

“enhance”: “enhance info”

}

Java中解析JWT中的内容


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

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

io.jsonwebtoken

jjwt

0.9.1

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

@RestController

@RequestMapping(“/user”)

public class UserController {

@GetMapping(“/getCurrentUser”)

public Object getCurrentUser(Authentication authentication, HttpServletRequest request) {

String header = request.getHeader(“Authorization”);

String token = StrUtil.subAfter(header, “bearer”, false);

return Jwts.parser()

.setSigningKey(“test_key”.getBytes(StandardCharsets.UTF_8))

.parseClaimsJws(token)

.getBody();

}

}

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

在这里插入图片描述

刷新令牌


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

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

@Configuration

@EnableAuthorizationServer

public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Override

public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

clients.inMemory()

// 配置client_id

.withClient(“admin”)

// 配置client_secret

  • 16
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值