我正在使用客户提供的凭据从另一个系统检索 token 。检索 token 后,我将创建一个 UsernamePasswordAuthenticationToken
并将其放入 SecurityContextHolder 中。
我还想存储 token ,因为我需要它来执行 API 调用。我应该将 token 放在哪里? 我不喜欢将 token 放入 UsernamePasswordAuthenticationToken
的 password
属性中。
您可以找到以下代码:
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")
}
最佳答案
为了解决这个问题,我提供了自己的 Principal
实现:
data class UserInfo(val email: String, val token: String) : Principal {
override fun getName(): String = email
}
然后将 UserInfo
实例传递给 UsernamePasswordAuthenticationToken
构造函数:
UsernamePasswordAuthenticationToken(UserInfo(email, token), password, listOf(SimpleGrantedAuthority("USER")))
如果您需要此 token ,您将能够使用一行简单的代码从 SecurityContext
检索它:
(SecurityContextHolder.getContext().authentication.principal as UserInfo).token
关于java - 如何在Spring应用程序中存储从另一个系统检索到的 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58337186/