简体   繁体   English

Spring Security 在注册时设置角色

[英]Spring Security Set Role On Registration

I'm new to Spring security, so I've followed some tutorials but I'm having trouble understanding how the structure of roles really works under the hood.我是 Spring security 的新手,所以我已经学习了一些教程,但是我无法理解角色的结构是如何真正在幕后工作的。 I have two tables, one for the User:我有两张表,一张给用户:

        @Entity
        @Table(name = "UserProfile", schema = "dbo", catalog = "DevTestTeam")
        public class UserProfileEntity implements UserDetails{

            @Id
            @GeneratedValue(strategy = GenerationType.IDENTITY)
            @Column(name = "id", nullable = false)
            private long id;

            @Column(name = "enabled", nullable = false)
            private boolean enabled;

            @NotEmpty(message = "Enter a password.")
            @Size(min = 6, max = 15, message = "Password must be between 6 and 15 characters.")
            @Column(name = "password", nullable = true, length = 100)
            private String password;

            @NotEmpty(message = "Enter a username.")
            @Size(min = 6, max = 20, message = "Username must be between 6 and 20 characters.")
            @Column(name = "username", nullable = true, length = 20, unique = true)
            private String username;

            @OneToOne
            @JoinColumn(name = "role_id")
            private RoleEntity role;

            public RoleEntity getRole() {
                return role;
            }

            public void setRole(RoleEntity role) {
                this.role = role;
            }

            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                List<GrantedAuthority> authorities = new ArrayList<>();
                authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
                return authorities;
            }

and one for the role:和一个角色:

@Entity
@Table(name = "Role", schema = "dbo", catalog = "DevTestTeam")
public class RoleEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private long id;

@Column(name = "name", nullable = true, length = 255)
private String name;

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

My confusion comes when creating a new user.创建新用户时,我感到困惑。 I have a registration form backed by a UserProfileEntity object, and that populates the username and password.我有一个由 UserProfileEntity 对象支持的注册表单,它填充了用户名和密码。 Then obviously it's easy to setEnabled()=true (I left some of the getters/setters out of this code for clarity).然后显然很容易 setEnabled()=true (为了清楚起见,我在这段代码中留下了一些 getter/setter)。

My question is how to set the role when instantiating a UserProfileEntity to be saved in the database.我的问题是在实例化要保存在数据库中的 UserProfileEntity 时如何设置角色。 My role_id foreign key should just take an integer and return the role from the Role table, but I'm not sure how to express this when instantiating.我的 role_id 外键应该只取一个整数并从 Role 表返回角色,但我不确定在实例化时如何表达。 I have a ROLE_USER in the roles table with an id of 1, and I feel like this is pretty simple to instantiate but I can't find the answer I'm looking for.我在角色表中有一个 ROLE_USER,id 为 1,我觉得这很容易实例化,但我找不到我正在寻找的答案。

UserImpl:用户实现:

@Service
public class UserProfileServiceImpl implements UserProfileService{
@Autowired
private UserProfileDao userDao;

@Override
public UserProfileEntity findByUser(String username) {
    return userDao.findByUsername(username);
}

@Override
public List<UserProfileEntity> findAll() {
    List<UserProfileEntity> list = userDao.findAll();
    return list;
}

@Override
public UserProfileEntity save(UserProfileEntity persisted) {
    userDao.save(persisted);
    return null;
}

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    UserProfileEntity user = userDao.findByUsername(username);
    if (user == null) {
        throw new UsernameNotFoundException("User not found.");
    }

    return user;
}

} }

You'll need some repository method to obtain user role by name:您需要一些存储库方法来按名称获取用户角色:

RoleEntity roleEntity = roleEntityRepository.findByName("ROLE_USER");

Then set that RoleEntity to UserProfileEntity before persisting it:然后在持久化之前将该RoleEntity设置为UserProfileEntity

UserProfileEntity userProfileEntity = new UserProfileEntity();
userProfileEntity.setRoleEntity(roleEntity);
userService.save(userProfileEntity);

What you also want is to leave your UserProfileEntity unextended.您还想要的是不扩展您的UserProfileEntity For Spring Security, you'll need UserDetailsService implementation:对于 Spring Security,您需要UserDetailsService实现:

@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserProfileEntity userProfileEntity = userRepository.findByUsername(username);

        if (userProfileEntity == null) {
            throw new UsernameNotFoundException("Non existing user!");
        }

        return new org.springframework.security.core.userdetails.User(userProfileEntity.getUsername(),
                userProfileEntity.getPassword(),
                Arrays.asList(new SimpleGrantedAuthority(userByUsername.getRoleEntity().getName())));
    }

}

However, I see that your requirements are quite simple - one role per user.但是,我看到您的要求非常简单 - 每个用户一个角色。 Therefore, your RoleEntity could simply be an enum with predefined roles:因此,您的RoleEntity可能只是一个具有预定义角色的枚举:

public enum RoleEntity {
    ROLE_USER
}

And in UserProfileEntity you'd use it like this:UserProfileEntity您可以像这样使用它:

public class UserProfileEntity {
    @Enumerated(EnumType.STRING)
    private RoleEntity roleEntity;
}

To persist user with role:使用角色持久化用户:

UserProfileEntity userProfileEntity = new UserProfileEntity();
userProfileEntity.setRoleEntity(RoleEntity.USER);
userService.save(userProfileEntity);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM