当前位置:网站首页>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 !
边栏推荐
- BeanDefinitionRegistryPostProcessor
- Download the corresponding version of chromedriver
- QT read write excel -- qxlsx insert chart 5
- [untitled]
- Final review (Day5)
- Understand expectations (mean / estimate) and variances
- pytorch DataLoader实现miniBatch(未完成)
- Kubernetes notes (III) controller
- Final review (Day6)
- [explain in depth the creation and destruction of function stack frames] | detailed analysis + graphic analysis
猜你喜欢

理解 YOLOV1 第一篇 预测阶段

Kubernetes notes (III) controller
![Ensemble, série shuishu] jour 9](/img/39/c1ba1bac82b0ed110f36423263ffd0.png)
Ensemble, série shuishu] jour 9
![[Shangshui Shuo series together] day 10](/img/a3/e8b9df588bef67ead925813a75c8c0.png)
[Shangshui Shuo series together] day 10

The most responsible command line beautification tutorial

Apache+php+mysql environment construction is super detailed!!!

pytorch 多分类中的损失函数

Analysis of the example of network subnet division in secondary vocational school

Synthetic keyword and NBAC mechanism

Redhat7 system root user password cracking
随机推荐
Ensemble, série shuishu] jour 9
项目总结--2(Jsoup的基本使用)
[set theory] relational closure (reflexive closure | symmetric closure | transitive closure)
Simple solution of small up main lottery in station B
Detailed explanation of contextclassloader
Multithreading and high concurrency (7) -- from reentrantlock to AQS source code (20000 words, one understanding AQS)
[Shangshui Shuo series together] day 10
[untitled]
Kubernetes notes (VI) kubernetes storage
Troubleshooting of 32GB Jetson Orin SOM failure to brush
PMP笔记记录
SVN分支管理
Txt document download save as solution
Method of finding prime number
Redhat7系统root用户密码破解
Simple handwritten ORM framework
[Zhao Yuqiang] deploy kubernetes cluster with binary package
Niuke JS separator
Synthetic keyword and NBAC mechanism
Disruptor learning notes: basic use, core concepts and principles