具有特定表Role的spring Security UserDetailsS ervice

问题描述 投票:1回答:2

我正在创建一个必须使用Spring Security登录的应用程序。它是标准的login/logout,我发现了很多教程如何创建它。什么不标准 - 是数据库中的表角色。我无法更改数据库,我可以使用它。我为用户和角色制作了正确的实体,但我无法顺利,如何用UserDetailsServiceImpl正确编写loadUserByUsername。我找不到一个接近的东西......

实体:

    @Entity
    @Table(name = "user")
    public class User implements model.Entity {

    @Id
    @GeneratedValue
    @Column(name = "userId", nullable = false)
    private int userId;

    @Column(name = "firstName")
    private String firstName;

    @Column(name = "lastName")
    private String lastName;

    @Column(name = "login", nullable = false)
    private String login;

    @Column(name = "password", nullable = false)
    private String password;

    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(name = "roleId", nullable = false)
    private Set<Role> roleId;

    @Transient
    private String confirmPassword;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Set<Role> getRoleId() {
        return roleId;
    }

    public void setRoleId(Set<Role> roleId) {
        this.roleId = roleId;
    }
 }

角色:

    @Entity
    @Table(name = "role")
    public class Role implements model.Entity {
    @Id
    @GeneratedValue
    @Column(name = "roleId", nullable = false)
    private int roleId;

    @Column(name = "user")
    private boolean user;

    @Column(name = "tutor")
    private boolean tutor;

    @Column(name = "admin")
    private boolean admin;

    public Role() {} // Empty constructor to have POJO class

    public int getRoleId() {
        return roleId;
    }

    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }

    public boolean isUser() {
        return user;
    }

    public void setUser(boolean user) {
        this.user = user;
    }

    public boolean isTutor() {
        return tutor;
    }

    public void setTutor(boolean tutor) {
        this.tutor = tutor;
    }

    public boolean isAdmin() {
        return admin;
    }

    public void setAdmin(boolean admin) {
        this.admin = admin;
    }

    @Override
    public String toString() {
        return "Role{" +
                "roleId=" + roleId +
                ", user='" + user + '\'' +
                ", tutor=" + tutor + '\'' +
                ", admin=" + admin +
                '}';
    }
}

所以主要的问题是如何创建实现UserDetailsS​​ervice的UserDetailServiceImpl的实现:

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ...
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        ...
        return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), grantedAuthorities);
    }

也许我应该创建特殊的类,它返回用户的确切角色..或者可能有另一种方法?

我不要求为我编码,只是帮我说一下如何让它更好地实现这样的角色。主要目标是划分AdminTutorUser

spring web-applications spring-security user-roles userdetailsservice
2个回答
0
投票

鉴于我在某种程度上同意holmis83评论,因为实际上可能存在某些情况下role表在某些组合中可能有奇怪(或至少,重复甚至相互矛盾)的信息,有几种方法可以采取。

首先,我建议你在数据库中创建一个视图来处理role表,它会更加友好authorities-by-username-query

我会这样做:

SELECT roleId, 'ROLE_USER' as role FROM role WHERE user = 1
UNION
SELECT roleId, 'ROLE_TUTOR' as role FROM role WHERE tutor = 1
UNION
SELECT roleId, 'ROLE_ADMIN' as role FROM role WHERE admin = 1;

就这样,对于像这样的数据库模型

enter image description here

你会得到这样的结果:

enter image description here

现在,你可以让你的authorities-by-username-query使用新创建的视图而不是原始表格从用户制作inner join

SELECT user.login, roles_view.role FROM user as user 
INNER JOIN user_has_role as user_role ON user.userId = user_role.user_userId 
INNER JOIN roles_view ON user_role.role_roleId = roles_view.roleId 

这将是输出:

username  |  role
----------------------
jlumietu  | ROLE_USER
jlumietu  | ROLE_ADMIN
username  | ROLE_USER
username  | ROLE_TUTOR
username  | ROLE_ADMIN
username  | ROLE_ADMIN
username  | ROLE_USER
username  | ROLE_TUTOR
username  | ROLE_ADMIN
username  | ROLE_TUTOR

由于可能存在一些重复的信息,您可以通过使用用户名和角色来创建一个组,就这样:

SELECT user.login, roles_view.role FROM user 
INNER JOIN user_has_role as user_role ON user.userId = user_role.user_userId 
INNER JOIN roles_view
ON user_role.role_roleId = roles_view.roleId 
GROUP BY login, role;

只是为了得到这个结果:

username  |  role
----------------------
jlumietu  | ROLE_ADMIN
jlumietu  | ROLE_USER
username  | ROLE_ADMIN
username  | ROLE_TUTOR
username  | ROLE_USER

实际上,没有必要这样做,因为Spring安全性会处理它以避免重复的角色,但为了便于阅读,如果查询是手动执行的,我认为这是值得的。

一旦说完这一切,让我们检查一下安全配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security.xsd">


    <security:http use-expressions="true" authentication-manager-ref="authenticationManager">

        <security:intercept-url pattern="/simple/**" access="permitAll()" />
        <security:intercept-url pattern="/secured/**" access="isAuthenticated()" />

        <security:form-login 
            login-page="/simple/login.htm"
            authentication-failure-url="/simple/login.htm?error=true"
            default-target-url="/secured/home.htm"
            username-parameter="email" 
            password-parameter="password"
            login-processing-url="/secured/performLogin.htm" />

        <security:logout 
            logout-url="/secured/performLogout.htm"
            logout-success-url="/simple/login.htm" />

        <security:csrf disabled="true" />

    </security:http>

    <security:authentication-manager id="authenticationManager">

        <security:authentication-provider>      
            <security:password-encoder hash="md5" />
            <security:jdbc-user-service id="jdbcUserService" data-source-ref="dataSource"
                users-by-username-query="
                    SELECT login AS username, password AS password, '1' AS enabled 
                    FROM user           
                    WHERE user.login=?" 
                authorities-by-username-query="
                    SELECT user.login, roles_view.role 
                    FROM user 
                    INNER JOIN user_has_role as user_role ON user.userId = user_role.user_userId 
                    INNER JOIN roles_view ON user_role.role_roleId = roles_view.roleId 
                    where user.login = ?
                    GROUP BY login, role"
            />          
        </security:authentication-provider>
    </security:authentication-manager>

</beans:beans>

即使您无法在数据库中创建视图,您也可以设法在role中的authorities-by-username query表中键入select-union sql。

请注意,使用此解决方法,您甚至不需要编写自定义的UserDetailsService


0
投票

我做了类似的事情,虽然我的用户只能有一个角色。

@Override
@Transactional
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
    final User user = Optional.ofNullable(findUserByEmail(username)).orElseThrow(() -> new UsernameNotFoundException("User was not found"));
    List<GrantedAuthority> authorities = getUserAuthority(user.getRole());
    final boolean canLogin = user.isActive() && user.isVerified();
    if (!canLogin) {
        throw new AccountException("User is not enabled");
    }
    return buildUserForAuthentication(user, authorities);
}

private List<GrantedAuthority> getUserAuthority(final Role userRole) {
    return Collections.singletonList(new SimpleGrantedAuthority(userRole.getRole()));
}

private UserDetails buildUserForAuthentication(final User user, final List<GrantedAuthority> authorities) {
    return new org.springframework.security.core.userdetails.User(
            user.getEmail(),
            user.getPassword(),
            true,
            true,
            true,
            true,
            authorities);
}

您可以将getUserAuthority调整为类似于:

    private List<GrantedAuthority> getUserAuthorities(final Set<Role> roles) {
    return roles.stream().map(roleId -> {
        final Role role = roleRepository.findOne(roleId);
        if (role.isAdmin) {
            return new SimpleGrantedAuthority("ROLE_ADMIN");    
        } else if (role.isUser) {
            return new SimpleGrantedAuthority("ROLE_USER");
        }
        // like wise for all your roles.
    }).collect(Collectors.toList());
}
© www.soinside.com 2019 - 2024. All rights reserved.