Ricardo Raz
Ricardo Raz

Reputation: 523

Single Role Spring Security Implementation

I've been working on spring boot mini-project and I'm stuck at this part.

So our project may contain many users but each user can only have one role

There are three roles:

ERD included:

ERD

My question is can I implement Spring security registration and authorization based on my ERD because from what I've seen from tutorials in the internet has many-to-many relationship between user and role entity or my ERD is wrong?

Hopefully someone could enlighten me.

Upvotes: 1

Views: 1510

Answers (1)

Michal
Michal

Reputation: 2273

Yes you can.

  1. Create your own implementation of Authentication
  2. The interface defineds method getAuthorities(). It returns a Collection but it's up to you how you implement it.
  3. Make sure your Login filter (or whatever authentication mechanism you may have in place) returns your custom AuthenticatedUser (instead of a UsernamePasswordAuthenticationToken you may find in examples)

Example:

public class AuthenticatedUser implements Authentication{
    private User user;
    public AuthenticatedUser(User user){
        this.user = user;
    }
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Arrays.asList(new SimpleGrantedAuthority(user.getRole()));
    } 
    // rest of the code omitted
}

I'm not sure I understand your reference to registration - user registration is usually a custom implementation anyway; you shouldn't have any issues there.

Upvotes: 3

Related Questions