Crovitz
Crovitz

Reputation: 51

Add claims to the token in Spring Security after retrieving a user

I use Spring Authorization Server v.1.0.0. I'd like to to add claims like eg. User ID, after I retrieve user from a database. I have my own implementation of UserDetailsService:

override fun loadUserByUsername(username: String): IamUserDetails {
    return userRepository.findByEmail(username)
            ?.let { IamUserDetails(it) } ?: throw UsernameNotFoundException(username)
}

and my extended user model looks like this:

data class IamUserDetails(
private val user: User,
) : UserDetails {

    override fun getAuthorities(): MutableCollection<out GrantedAuthority> = mutableListOf()
    
    override fun getPassword() = user.password
    
    override fun getUsername() = user.email
    
    override fun isAccountNonExpired() = true
    
    override fun isAccountNonLocked() = true
    
    override fun isCredentialsNonExpired() = true
    
    override fun isEnabled() = user.enabled
}

The user property contains id of the user from the database. Currently the token looks like this:

{
"sub": "[email protected]",
"aud": "messaging-client",
"nbf": 1670443075,
"scope": \[
"openid"
\],
"iss": "http://localhost:8080",
"exp": 1670443375,
"iat": 1670443075
}

The question is how to enrich this token with claim userId?

Upvotes: 1

Views: 1027

Answers (1)

Crovitz
Crovitz

Reputation: 51

I found a solution for the problem. I've seen a lot of examples with overriding jwtDecoder bean but it doesn't work with Spring Authorization Server.

I've added:

@Bean
fun tokenCustomizer(): OAuth2TokenCustomizer<JwtEncodingContext> {
    return TokenCustomizer()
}

and implementation like:

class TokenCustomizer : OAuth2TokenCustomizer<JwtEncodingContext> {

    override fun customize(context: JwtEncodingContext) {
        context.claims.claims { it["test"] = "test" }
    }
}

then JWT contains:

{
  "sub": "[email protected]",
  "aud": "messaging-client",
  "nbf": 1670596440,
  "test": "test",
  "scope": [
    "openid"
  ],
  "iss": "http://localhost:8080",
  "exp": 1670596740,
  "iat": 1670596440
}

Upvotes: 1

Related Questions