Reputation: 302
I'm retrieving token from another system using credentials provided by customer. After the token is retrieved I'm creating a UsernamePasswordAuthenticationToken
and put it into SecurityContextHolder.
I would like to store the token as well because I'll need it to perform the API calls. Where do I put the token? I don't like the idea of putting the token to the password
property of the UsernamePasswordAuthenticationToken
.
You can find the code below:
override fun authenticate(authentication: Authentication?): Authentication {
authentication?.let {
val email = authentication.name
val password = authentication.credentials.toString()
val token = authenticationSource.getAuth(email, password) // I want to store it somewhere!
return UsernamePasswordAuthenticationToken(email, password, listOf(SimpleGrantedAuthority("USER")))
}
throw AuthenticationServiceException("Authentication object is equal null")
}
Upvotes: 1
Views: 1265
Reputation: 302
In order to solve this problem I've provided my own Principal
implementation:
data class UserInfo(val email: String, val token: String) : Principal {
override fun getName(): String = email
}
and then passed the instance of UserInfo
to the UsernamePasswordAuthenticationToken
constructor :
UsernamePasswordAuthenticationToken(UserInfo(email, token), password, listOf(SimpleGrantedAuthority("USER")))
And if you need this token you will be able to retrieve it from the SecurityContext
the with a simple line of code:
(SecurityContextHolder.getContext().authentication.principal as UserInfo).token
Upvotes: 1