'How to refresh OAuth token and switch user in Spring Security 2.2.3?
I need similar functionality as Google/YouTube that lets you switch user account that belongs also to you.
There is authentication server based on Spring Security.
How it works now:
- User enters login and password in web application
- Web application sends his credentials to authentication server and receives JWT token
POST /token?username=user&password=pass&grant_type=password&scope=read
- When we have JWT token, it's included as Authorization Bearer header in every HTTP request
- User wants to switch account without re-entering login and password - we need to get other account's JWT
When you add your own endpoint, Principal is null:
@PostMapping("/switch")
public void switchUser(Principal principal) {
System.out.println(principal);
}
If Principal was set (based on existing JWT token sent in Authorization Bearer header), I could manually get user from database, verify if requested account belongs to user and generate JWT token.
There is also no way to refresh existing token - no refresh token comes in response.
This is configuration below:
@Configuration
@EnableAuthorizationServer
@RequiredArgsConstructor
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
private final AuthenticationManager authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.authenticationManager(authenticationManager)
.tokenStore(tokenStore())
.accessTokenConverter(converter());
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("client_name")
.secret("{noop}client_secret_phrase")
.authorizedGrantTypes("client_password")
.scopes("read");
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(converter()); // converter used to add more fields
}
@Bean
public JwtAccessTokenConverter converter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter() {
@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
var token = (DefaultOAuth2AccessToken) super.enhance(accessToken, authentication);
/* ....... adding more fields here ........ */
token.setAdditionalInformation(info);
return token;
}
};
/* ...... loading key store here ...... */
return converter;
}
}
Does Spring support any functionality of switching user accounts based on JWT token? How to read existing JWT token and get user credentials based on the JWT? Do I need to write additional filter or to configure extra Spring Security features?
TL;DR: Having existing JWT token, I need to generate JWT for another account that belongs to user.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
