krtkush
krtkush

Reputation: 1528

How to provide role saved in DB as GrantedAuthority in UserDetails implementation?

I have a UserDetail implementation -

class AuthUserDetails(val user: UserEntity): UserDetails {

    override fun getAuthorities(): Collection<GrantedAuthority?>? {
        return listOf(SimpleGrantedAuthority("ROLE_ADMIN"))
    }

    override fun getPassword(): String? {
        return user.password
    }

    override fun getUsername(): String? {
        return user.userName
    }

    override fun isEnabled(): Boolean {
        return user.isActive
    }

    override fun isAccountNonExpired(): Boolean {
        return true
    }

    override fun isAccountNonLocked(): Boolean {
        return true
    }

    override fun isCredentialsNonExpired(): Boolean {
        return true
    }
}

My UserEntity is as follows -

@Entity
@Table(name = "users")
class UserEntity(@Column(name = "user_id", nullable = false)
                 @Id @GeneratedValue(strategy = GenerationType.AUTO)
                 var id: Long = 0,
                 @Column(name = "user_roles", nullable = false)
                 var roles: String = "admin")

As you can see I have hard coded the return type of getAuthorities() as "ROLE_ADMIN". However, I would want to pick the role saved in the DB under user_roles columns and provide that as SimpleGrantedAuthority. How do I do that?

Upvotes: 0

Views: 1579

Answers (1)

Why would you want to do that? SimpleGrantedAuthority is a spring security class and not a good idea to mix with your domain model. Anyway you can do it like this.

  • Write a jpa AttributeConverter for SimpleGrantedAuthority
    import org.springframework.security.core.authority.SimpleGrantedAuthority;

    import javax.persistence.AttributeConverter;
    import javax.persistence.Converter;
    import java.util.Optional;

    @Converter
    public class SimpleGrantedAuthorityConverter implements
        AttributeConverter<SimpleGrantedAuthority, String> {

      @Override
      public String convertToDatabaseColumn(SimpleGrantedAuthority authority) {
        return Optional.ofNullable(authority)
                .map(SimpleGrantedAuthority::getAuthority)
                .orElse(null);
      }

      @Override
      public SimpleGrantedAuthority convertToEntityAttribute(String role) {
        return Optional.ofNullable(role)
                .map(SimpleGrantedAuthority::new)
                .orElse(null);
       }
    }
  • Annotate the field in the UserEntity with equivalent of :
     @Convert(converter = SimpleGrantedAuthorityConverter.class)
     private SimpleGrantedAuthority role;

Note

Spring secuirty's design, a user can have multiple roles but I noted your are storing only single role. I assume that is your business case.

Upvotes: 1

Related Questions