How can I write spring security without using any role table in the database?

I have the following classes:

class User{
     private int id;
     private String email;
     private String password;
}

class Admin extends User{
     // the same fields as in User class
}

class REDAdmin extends User{
     private String company;
     private String description;
}

class Customers extends User{
     private String FirstName;
     private String LastName;
     ....
}

In my db I don't need context.xml security role table

'http://www.springframework.org/schema/beans/spring - beans -3.0.xsd    http://www.springframework.org/schema/security   http://www.springframework.org/schema/security/spring -security-3.2.xsd ">

<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
    <intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
    <intercept-url pattern="/REDadmin**" access="hasRole('ROLE_REDADMIN')" />
    <intercept-url pattern="/user**" access="hasRole('ROLE_USER')" />

    <!-- access denied page -->
    <access-denied-handler error-page="/403" />
    <form-login 
        login-page="/login" 
        default-target-url="/welcome" 
        authentication-failure-url="/login?error" 
        username-parameter="username"
        password-parameter="password" />
    <logout logout-success-url="/login?logout"  />
    <!-- enable csrf protection -->
    <csrf/>
</http>

+4
source share
1 answer

If you do not need to manage roles using a relationship, you can return a fixed set of roles to entity classes. The user / account must execute the UserDetails contract - for example:

class User implements UserDetails {

    private final Set<GrantedAuthority> authorities = new HashSet<>();

    public User() {
        authorities.add(new SimpleGrantedAuthority("USER"));
        // ... add further roles if required
    }

    public Collection<GrantedAuthority> getAuthorities() {
        return authorities;
    }

    ...
}

: GrantedAuthority, SimpleGrantedAuthority

+1

Source: https://habr.com/ru/post/1627167/


All Articles