当前位置:网站首页>Oauth2.0 - using JWT to replace token and JWT content enhancement
Oauth2.0 - using JWT to replace token and JWT content enhancement
2022-07-03 06:02:00 【Xiao bichao】
One 、OAuth2.0
In the last article, we explained OAuth2.0 Several authentication modes , The previous explanation Token use OAuth2.0 Generated in its own way Token, But this way also has this drawback , Through the previous test, we found , When the resource service and authorization service are not together, the resource service uses RemoteTokenServices Remote request authorization service authentication token, If the number of visits is large, it will affect the performance of the system .
So we can use JWT To generate the token , User authentication will get a JWT token ,JWT The token already contains user related information , The client just needs to carry JWT Access resource services , The resource service completes the token verification by itself according to the agreed algorithm , There is no need to request the authentication service to complete authorization every time .
Here is the address of the last article :
Two 、OAuth2.0 Integrate JWT
This article continues to revise the content of the previous article .
Authentication service modification
First of all JWT Signature mode , Symmetric encryption is adopted here , Set key to bxc123, This is also modified in the resource server :
@Configuration
public class TokenConfig {
private String SIGNING_KEY = "bxc123";
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
converter.setSigningKey(SIGNING_KEY); // Symmetric key , The resource server uses the secret key to verify
return converter;
}
}
Next, we need to modify AuthorizationServer Preparation Class , The main AuthorizationServerTokenServices The preparation of , Add one more TokenEnhancerChain, Declare the above JwtAccessTokenConverter Prepare it .
@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
@Autowired
private TokenStore tokenStore;
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private AuthorizationCodeServices authorizationCodeServices;
@Autowired
private JwtAccessTokenConverter accessTokenConverter;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()// Use in‐memory Storage
.withClient("c1")// client_id
.secret(new BCryptPasswordEncoder().encode("secret"))
.resourceIds("res1")
.authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")// The client Allowed authorization types authorization_code,password,refresh_token,implicit,client_credentials
.scopes("all")// Permitted scope of Authorization
.autoApprove(false) // Add the verification callback address
.authorities("admin")
.redirectUris("http://www.baidu.com");
}
// Set how the authorization code of the authorization code mode is accessed , Temporarily use memory mode
@Bean
public AuthorizationCodeServices authorizationCodeServices() {
return new InMemoryAuthorizationCodeServices();
}
@Bean
public AuthorizationServerTokenServices tokenService() {
DefaultTokenServices service = new DefaultTokenServices();
service.setClientDetailsService(clientDetailsService);
service.setSupportRefreshToken(true);
service.setTokenStore(tokenStore);
// Token enhancement
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
List<TokenEnhancer> tokenEnhancers = new ArrayList<>();
tokenEnhancers.add(accessTokenConverter);
tokenEnhancerChain.setTokenEnhancers(tokenEnhancers);
service.setTokenEnhancer(tokenEnhancerChain);
service.setAccessTokenValiditySeconds(7200); // Token default validity 2 Hours
service.setRefreshTokenValiditySeconds(259200); // Refresh token default validity 3 God
return service;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
.authenticationManager(authenticationManager)// Authentication manager
.authorizationCodeServices(authorizationCodeServices)// Authorization code service
.tokenServices(tokenService())// Token management service
.allowedTokenEndpointRequestMethods(HttpMethod.POST);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security
.tokenKeyAccess("permitAll()") //oauth/token_key It's public
.checkTokenAccess("permitAll()") //oauth/check_token Open
.allowFormAuthenticationForClients(); // Forms authentication ( Claim Token )
}
}
restart auth Certification services .
Resource service modification
Put what's written on it TokenConfig class , Cover resource services , And modify it ResouceServerConfig Preparation Class , The logic of verifying the token by the remote access authentication service written above , It can be removed :
@Configuration
@EnableResourceServer
public class ResouceServerConfig extends ResourceServerConfigurerAdapter {
public static final String RESOURCE_ID = "res1";
@Autowired
TokenStore tokenStore;
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID)// resources id
.tokenStore(tokenStore)
.stateless(true);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasAuthority("admin")
.antMatchers("/common/**").hasAuthority("common")
.and().csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
Restart the resource service .
3、 ... and 、 test
Log in to the system in password mode to get token, You can see what you get token It's already Jwt Format :
Can be in some Jwt Online parsing website , Parsing JWT:
Use token Go to the resource service interface :
Four 、JWT Content enhancement
You can see up here JWT Some user information is placed by default , What if we want to store other things , Just use DefaultOAuth2AccessToken Of setAdditionalInformation Method , Pass a Map You can place customized data , You can get user information , You can also find other customized information placement , Next, modify the authentication service AuthorizationServer Preparation Class :
add to TokenEnhancer tokenEnhancer() Method :
/**
* JWT Content enhancement
*/
@Bean
public TokenEnhancer tokenEnhancer() {
return (accessToken, authentication) -> {
Map<String, Object> additionalInfo = new HashMap<>();
User principal = (User)authentication.getUserAuthentication().getPrincipal();
String username = principal.getUsername();
additionalInfo.put("three"," Additional content !");
((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
return accessToken;
};
}
In the build TokenEnhancerChain Object time , Put the settings configured above :
@Bean
public AuthorizationServerTokenServices tokenService() {
DefaultTokenServices service = new DefaultTokenServices();
service.setClientDetailsService(clientDetailsService);
service.setSupportRefreshToken(true);
service.setTokenStore(tokenStore);
// Token enhancement
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
List<TokenEnhancer> tokenEnhancers = new ArrayList<>();
// Content enhancement
tokenEnhancers.add(tokenEnhancer());
tokenEnhancers.add(accessTokenConverter);
tokenEnhancerChain.setTokenEnhancers(tokenEnhancers);
service.setTokenEnhancer(tokenEnhancerChain);
service.setAccessTokenValiditySeconds(7200); // Token default validity 2 Hours
service.setRefreshTokenValiditySeconds(259200); // Refresh token default validity 3 God
return service;
}
Restart the authentication service , Log in again , You can see that the added information already exists :
If the parsing JWT, You can also see the content :

Love little buddy can pay attention to my personal WeChat official account. , Get more learning materials !
边栏推荐
- Troubleshooting of 32GB Jetson Orin SOM failure to brush
- Kubernetes notes (VIII) kubernetes security
- Clickhouse learning notes (2): execution plan, table creation optimization, syntax optimization rules, query optimization, data consistency
- Redis encountered noauth authentication required
- Why should there be a firewall? This time xiaowai has something to say!!!
- Detailed explanation of iptables (1): iptables concept
- MySQL 5.7.32-winx64 installation tutorial (support installing multiple MySQL services on one host)
- PHP用ENV获取文件参数的时候拿到的是字符串
- [teacher Zhao Yuqiang] kubernetes' probe
- Bio, NiO, AIO details
猜你喜欢

Convolution operation in convolution neural network CNN
![[branch and cycle] | | super long detailed explanation + code analysis + a trick game](/img/aa/543d4f0dcbcd664be963579af77ec9.jpg)
[branch and cycle] | | super long detailed explanation + code analysis + a trick game
![[teacher Zhao Yuqiang] MySQL high availability architecture: MHA](/img/a7/2140744ebad9f1dc0a609254cc618e.jpg)
[teacher Zhao Yuqiang] MySQL high availability architecture: MHA

Alibaba cloud OOS file upload

Pytorch dataloader implements minibatch (incomplete)

phpstudy设置项目可以由局域网的其他电脑可以访问
![[teacher Zhao Yuqiang] kubernetes' probe](/img/cc/5509b62756dddc6e5d4facbc6a7c5f.jpg)
[teacher Zhao Yuqiang] kubernetes' probe
![[teacher Zhao Yuqiang] use the catalog database of Oracle](/img/0b/73a7d12caf955dff17480a907234ad.jpg)
[teacher Zhao Yuqiang] use the catalog database of Oracle

智牛股项目--04
![[set theory] relational closure (reflexive closure | symmetric closure | transitive closure)](/img/c8/2995c503e9dabae4e2cc704449e04f.jpg)
[set theory] relational closure (reflexive closure | symmetric closure | transitive closure)
随机推荐
Crontab command usage
[teacher Zhao Yuqiang] calculate aggregation using MapReduce in mongodb
Redhat7 system root user password cracking
理解 期望(均值/估计值)和方差
理解 YOLOV1 第一篇 预测阶段
Simple handwritten ORM framework
[minesweeping of two-dimensional array application] | [simple version] [detailed steps + code]
Understand the first prediction stage of yolov1
Ensemble, série shuishu] jour 9
Complete set of C language file operation functions (super detailed)
[explain in depth the creation and destruction of function stack frames] | detailed analysis + graphic analysis
Solve the 1251 client does not support authentication protocol error of Navicat for MySQL connection MySQL 8.0.11
Jetson AgX Orin platform porting ar0233 gw5200 max9295 camera driver
Jedis source code analysis (II): jediscluster module source code analysis
JDBC connection database steps
Why should there be a firewall? This time xiaowai has something to say!!!
Bernoulli distribution, binomial distribution and Poisson distribution, and the relationship between maximum likelihood (incomplete)
JS implements the problem of closing the current child window and refreshing the parent window
从 Amazon Aurora 迁移数据到 TiDB
Qt读写Excel--QXlsx插入图表5