Spring Security如何在用户注册时为用户设置角色

时间:2018-01-12 17:57:34

标签: java spring-boot spring-security registration roles

目前我正在使用Java开发基于Spring Boot的Web应用程序。我正在尝试为我的应用程序创建工作人员注册。说实话,这是我的第一个这样的应用程序,我真的不知道如何在注册时授予用户角色。我已经看了几个教程,但没有人展示如何授予角色,同时将新用户添加到数据库。

在我的数据库中,我有表格Worker和Role,如下所示。

在注册表单中,我有两个复选框:worker和admin,我想根据已选择的权限授予权限。

这就是我所拥有的:

Worker.java

@Id
@Column(name = "workerId")
@GeneratedValue(
        strategy= GenerationType.AUTO,
        generator="native"
)
@GenericGenerator(
        name = "native",
        strategy = "native"
)
private int workerId;

@Column(name = "login")
@NotEmpty
private String username;

@Column(name = "password")
@NotEmpty
private String password;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "workerId", fetch = FetchType.EAGER, orphanRemoval = true)
private Set<Role> roles;

WorkerRole.java

public enum WorkerRole {
WORKER,ADMIN;}

Role.java

@NotNull
@ManyToOne
@JoinColumn(name = "workerId")
private Worker workerId;

@Id
@Column(name = "role")
private String role;

//getters and setters

WorkerService.java

@PersistenceContext
EntityManager entityManager;

@Autowired
private WorkerRepository workerRepository;

@Autowired
public WorkerService(WorkerRepository workerRepository){
    this.workerRepository = workerRepository;
}

public Worker findByEmail(String email){
    return workerRepository.findByEmail(email);
}

public Optional<Worker> findByUsername(String username)
{
    return workerRepository.findByUsername(username);
}

public Worker findByConfirmationToken(String confirmationToken){
    return workerRepository.findByConfirmationToken(confirmationToken);
}

public void saveUser(Worker worker){
    workerRepository.save(worker);
}

public PasswordEncoder getPasswordEncoder() {
    return new PasswordEncoder() {
        @Override
        public String encode(CharSequence charSequence) {
            return charSequence.toString();
        }

        @Override
        public boolean matches(CharSequence charSequence, String s) {
            return true;
        }
    };
}

public Worker findByUname(String login){
    Worker worker = null;
    try{
        worker = entityManager.createQuery("select w from Worker w " +
                "where w.login = :login ", Worker.class)
                .setParameter("login", login)
                .getSingleResult();
    }catch (Exception e){
        System.out.println("No results found for that uname");
    }

    return worker;
}

CustomUserDetails.java

public CustomUserDetails(final Worker worker) {
    super(worker);
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {

    return getRoles()
            .stream()
            .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRole()))
            .collect(Collectors.toList());
}

@Override
public String getPassword() {
    return super.getPassword();
}

@Override
public String getUsername() {
    return super.getUsername();
}

@Override
public boolean isAccountNonExpired() {
    return true;
}

@Override
public boolean isAccountNonLocked() {
    return true;
}

@Override
public boolean isCredentialsNonExpired() {
    return true;
}

@Override
public boolean isEnabled() {
    return true;
}

CustomUserDetailsS​​ervice.java

@Autowired
private WorkerRepository workerRepository;


@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Optional<Worker> optionalUsers = workerRepository.findByUsername(username);

    optionalUsers
            .orElseThrow(() -> new UsernameNotFoundException("Worker not found"));
    return optionalUsers
            .map(CustomUserDetails::new)
            .get();
}

我认为这一切,我希望有人可以帮助我:)。

1 个答案:

答案 0 :(得分:1)

如果是你的话,你不需要Role课程。只需在List<WorkerRole> roles中使用Worker.java即可。 您也可以在UserDetails中实施Worker.java,而不是使用CustomUserDetails

假设您正在使用Thymeleaf,则需要多选下拉列表can be populated with enum values

在使用枚举值填充下拉列表后,您只需选择角色并创建新用户。