当前位置:网站首页>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 !
边栏推荐
- CAD插件的安装和自动加载dll、arx
- [Shangshui Shuo series together] day 10
- 一起上水碩系列】Day 9
- Configure DTD of XML file
- [teacher Zhao Yuqiang] RDB persistence of redis
- 从小数据量分库分表 MySQL 合并迁移数据到 TiDB
- Core principles and source code analysis of disruptor
- [untitled]
- Pytorch builds the simplest version of neural network
- Final review Day8
猜你喜欢

Kubernetes notes (IX) kubernetes application encapsulation and expansion

Method of finding prime number

从小数据量 MySQL 迁移数据到 TiDB

Solve the 1251 client does not support authentication protocol error of Navicat for MySQL connection MySQL 8.0.11

Sophomore dilemma (resumption)

Today, many CTOs were killed because they didn't achieve business
![[Shangshui Shuo series together] day 10](/img/a3/e8b9df588bef67ead925813a75c8c0.png)
[Shangshui Shuo series together] day 10

How does win7 solve the problem that telnet is not an internal or external command

最大似然估计,散度,交叉熵
![[escape character] [full of dry goods] super detailed explanation + code illustration!](/img/33/ec5a5e11bfd43f53f2767a9a0f0cc9.jpg)
[escape character] [full of dry goods] super detailed explanation + code illustration!
随机推荐
2022.DAY592
[teacher Zhao Yuqiang] use the catalog database of Oracle
[branch and cycle] | | super long detailed explanation + code analysis + a trick game
Redhat7系统root用户密码破解
Method of finding prime number
How does win7 solve the problem that telnet is not an internal or external command
[function explanation (Part 2)] | [function declaration and definition + function recursion] key analysis + code diagram
Complete set of C language file operation functions (super detailed)
2022.7.2day594
Kubernetes cluster environment construction & Deployment dashboard
Niuke JS separator
The programmer shell with a monthly salary of more than 10000 becomes a grammar skill for secondary school. Do you often use it!!!
卷积神经网络CNN中的卷积操作详解
Use telnet to check whether the port corresponding to the IP is open
Kubernetes notes (IX) kubernetes application encapsulation and expansion
[untitled]
Final review (day3)
从小数据量分库分表 MySQL 合并迁移数据到 TiDB
1. 两数之和
MySQL startup error: several solutions to the server quit without updating PID file