My Spring Boot-based web app authenticates against a remote REST api. To do so, I have extended AbstractUserDetailsAuthenticationProvider
like so:
public class RestAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
@Override
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
// TODO Auto-generated method stub
}
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
String password = (String) authentication.getCredentials();
Credentials creds = new Credentials();
creds.setUsername(username);
creds.setPassword(password);
RestTemplate template = new RestTemplate();
try {
ResponseEntity<Authentication> auth = template.postForEntity("http://localhost:8080/api/authenticate",
creds, Authentication.class);
if (auth.getStatusCode() == HttpStatus.OK) {
String token = auth.getHeaders().get("Authorization").get(0); // Great! Now what?
return new User(authentication.getName(), password,
Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
}
throw new BadCredentialsException("Failed to authenticate, server returned " + auth.getStatusCodeValue());
} catch (HttpClientErrorException e) { // Check for type of error
throw new BadCredentialsException(e.getStatusText());
}
}
}
This works great. However my problem is that subsequent access to the API will require the API key being provided in the RestTemplate
headers. This is the
line :
String token = auth.getHeaders().get("Authorization").get(0); // Great! Now what?
What I'm after is some way to persist that token at the session level for future access. Down the line, I'm trying to do something along the lines of:
SecurityContext context = SecurityContextHolder.getContext();
Authentication userDetails = context.getAuthentication() ;
where somehow userDetails
would contain the API key.
Any suggestions?
Thanks!