当前位置:网站首页>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 !
边栏推荐
- Kubernetes notes (VIII) kubernetes security
- Method of finding prime number
- Apt update and apt upgrade commands - what is the difference?
- Clickhouse learning notes (I): Clickhouse installation, data type, table engine, SQL operation
- Exception when introducing redistemplate: noclassdeffounderror: com/fasterxml/jackson/core/jsonprocessingexception
- Skywalking8.7 source code analysis (I): agent startup process, agent configuration loading process, custom class loader agentclassloader, plug-in definition system, plug-in loading
- Redhat7系统root用户密码破解
- Simple handwritten ORM framework
- phpstudy设置项目可以由局域网的其他电脑可以访问
- [video of Teacher Zhao Yuqiang's speech on wot] redis high performance cache and persistence
猜你喜欢

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

pytorch 多分类中的损失函数

@Import annotation: four ways to import configuration classes & source code analysis
![[teacher Zhao Yuqiang] use the catalog database of Oracle](/img/0b/73a7d12caf955dff17480a907234ad.jpg)
[teacher Zhao Yuqiang] use the catalog database of Oracle

Final review (Day5)

Jedis source code analysis (II): jediscluster module source code analysis

多线程与高并发(7)——从ReentrantLock到AQS源码(两万字大章,一篇理解AQS)

智牛股--03

pytorch 搭建神经网络最简版

Analysis of the example of network subnet division in secondary vocational school
随机推荐
C 语言文件操作函数大全 (超详细)
[teacher Zhao Yuqiang] MySQL flashback
一起上水碩系列】Day 9
Synthetic keyword and NBAC mechanism
Why is the website slow to open?
理解 期望(均值/估计值)和方差
Jedis source code analysis (II): jediscluster module source code analysis
[teacher Zhao Yuqiang] RDB persistence of redis
Btrfs and ext4 - features, strengths and weaknesses
88. Merge two ordered arrays
Final review (Day5)
[teacher Zhao Yuqiang] use the catalog database of Oracle
Txt document download save as solution
2022.DAY592
Why should there be a firewall? This time xiaowai has something to say!!!
Jetson AgX Orin platform porting ar0233 gw5200 max9295 camera driver
CAD插件的安裝和自動加載dll、arx
[teacher Zhao Yuqiang] kubernetes' probe
BeanDefinitionRegistryPostProcessor
Final review Day8