如何在不使用数据库中的任何角色表的情况下编写Spring Security?

4

我有下面这些类:

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

在我的数据库中,我不需要任何角色表。

security-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>


你的配置是什么样子? - hotzst
提供角色的一种方法是提供 SQL 查询,因此如果您能告诉我们用户、管理员等使用的数据库结构,那将非常有用。 - Ralph
https://drive.google.com/file/d/0B3ZiZTsIESiSVVlNTFVUV1ZSanM/view - Roma
你的 security-config 目前是什么样子? - fateddy
我不知道如何编写 authentication-manager 和 authentication-provider。 - Roma
显示剩余2条评论
1个回答

6

如果您不需要使用关系管理角色,则可以在实体类中返回一组固定的角色。用户/账户应该实现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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接