当前位置:网站首页>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 !
边栏推荐
- Analysis of the example of network subnet division in secondary vocational school
- Installation of CAD plug-ins and automatic loading of DLL and ARX
- Why should there be a firewall? This time xiaowai has something to say!!!
- 2022.DAY592
- 1. 两数之和
- MySQL 5.7.32-winx64 installation tutorial (support installing multiple MySQL services on one host)
- Error 1045 (28000) occurs when Linux logs in MySQL: access denied for user 'root' @ 'localhost' (using password: yes)
- [escape character] [full of dry goods] super detailed explanation + code illustration!
- 【一起上水硕系列】Day 10
- [untitled]
猜你喜欢
Bio, NiO, AIO details
项目总结--04
pytorch DataLoader实现miniBatch(未完成)
Pytorch dataloader implements minibatch (incomplete)
Apache+php+mysql environment construction is super detailed!!!
Strategy pattern: encapsulate changes and respond flexibly to changes in requirements
Method of finding prime number
[Zhao Yuqiang] deploy kubernetes cluster with binary package
Es remote cluster configuration and cross cluster search
[teacher Zhao Yuqiang] MySQL high availability architecture: MHA
随机推荐
SVN分支管理
Es remote cluster configuration and cross cluster search
2022.DAY592
Installation of CAD plug-ins and automatic loading of DLL and ARX
Exception when introducing redistemplate: noclassdeffounderror: com/fasterxml/jackson/core/jsonprocessingexception
Kubernetes notes (VI) kubernetes storage
Kubernetes cluster environment construction & Deployment dashboard
Introduction to redis using Lua script
Solve the problem that Anaconda environment cannot be accessed in PowerShell
How does win7 solve the problem that telnet is not an internal or external command
[teacher Zhao Yuqiang] Alibaba cloud big data ACP certified Alibaba big data product system
Multithreading and high concurrency (7) -- from reentrantlock to AQS source code (20000 words, one understanding AQS)
[trivia of two-dimensional array application] | [simple version] [detailed steps + code]
Complete set of C language file operation functions (super detailed)
C 语言文件操作函数大全 (超详细)
There is no one of the necessary magic skills PXE for old drivers to install!!!
Understand the first prediction stage of yolov1
Using the ethtool command by example
Leetcode solution - 02 Add Two Numbers
Simple handwritten ORM framework