简体   繁体   中英

Spring, Oauth2: authentication details lost after refreshing the token

I have two Spring applications: an Authentication Service and a Business Service .

When a webservice user authenticates at the Authentication Service , he gets an access_token and a refresh_token . He can refresh his access_token by sending the refresh_token to the service. The service implements AuthenticationProvider , there the details of the authentication are set:

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException { 
    UsernamePasswordAuthenticationToken newAuthentication = ...;
    LinkedHashMap<String, Object> detailsMap = (LinkedHashMap<String, Object>) authentication.getDetails();
    detailsMap.put(...);
    newAuthentication.setDetails(detailsMap);
    return newAuthentication;
}

The Business Service is secured by Oauth2 . Its controller contains

@Secured({ SOME_ROLE })
@RequestMapping(...)
public ResponseEntity<?> doSomething(OAuth2Authentication authentication) {
    LinkedHashMap<String, String> detailsMap = (LinkedHashMap<String, String>) authentication
            .getUserAuthentication().getDetails();

If the webservice user authenticates at the Authentication Service and calls the Business Service , detailsMap will contain the information set in authenticate() . But if he refreshes the token and calls the Business Service again, detailsMap will be null .

I want the detailsMap to be preserved after the token has been refreshed. How can I achieve this?

As a workaround we do not use the details anymore, but save their data into the UserDetails implementation UserDetailsImplementation .

In the method Authentication authenticate(Authentication authentication) of the AuthenticationProvider implementation we return a UsernamePasswordAuthenticationToken whose principal is set to UserDetailsImplementation . This UserDetailsImplementation is also returned in the UserDetailsService implementation which is called at the refreshing of the token.

In the Business Service we can access the desired data by

((UserDetailsImplementation) authentication.getPrincipal()).getDesiredData();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM