java – 如何在不使用数据库中的任何角色表的情况下编写spring安全性?

我接下来的课程: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 compan...

我接下来的课程:

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;
     ....
}

在我的数据库中,我不需要任何Role表
安全的context.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    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>

解决方法:

如果您不需要使用关系管理角色,则可以在实体类中返回一组固定的角色.用户/帐户应实施UserDetails合同 – 例如:

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

本文标题为:java – 如何在不使用数据库中的任何角色表的情况下编写spring安全性?

基础教程推荐