title: Spring Security how to set roles for user while user registration
body: <p>currently I'm working on a Spring Boot based web application in Java. I'm trying to create worker registration for my application. To be honest this is my first application like this and I don't really know how to grant user roles while registration. I've watched a couple of tutorials, but no one shows how to grant roles, while adding new user to database.</p>
  
  <p>In my database I have tables Worker and Role like below.</p>
  
  <p>In registration form I have two checkboxes: worker and admin and I would like to grant permissions depending on which ones have been selected . </p>
  
  <p>This is what I have:</p>
  
  <p><strong>Worker.java</strong></p>
  
  <pre><code>@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&lt;Role&gt; roles;
  </code></pre>
  
  <p><strong>WorkerRole.java</strong></p>
  
  <pre><code>public enum WorkerRole {
  WORKER,ADMIN;}
  </code></pre>
  
  <p><strong>Role.java</strong></p>
  
  <pre><code>@NotNull
  @ManyToOne
  @JoinColumn(name = "workerId")
  private Worker workerId;
  
  @Id
  @Column(name = "role")
  private String role;
  
  //getters and setters
  </code></pre>
  
  <p><strong>WorkerService.java</strong></p>
  
  <pre><code>@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&lt;Worker&gt; 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;
  }
  </code></pre>
  
  <p><strong>CustomUserDetails.java</strong></p>
  
  <pre><code>public CustomUserDetails(final Worker worker) {
      super(worker);
  }
  
  @Override
  public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {
  
      return getRoles()
              .stream()
              .map(role -&gt; 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;
  }
  </code></pre>
  
  <p><strong>CustomUserDetailsService.java</strong></p>
  
  <pre><code>@Autowired
  private WorkerRepository workerRepository;
  
  
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
      Optional&lt;Worker&gt; optionalUsers = workerRepository.findByUsername(username);
  
      optionalUsers
              .orElseThrow(() -&gt; new UsernameNotFoundException("Worker not found"));
      return optionalUsers
              .map(CustomUserDetails::new)
              .get();
  }
  </code></pre>
  
  <p>I think that's all, I hope somebody can help me :)</p>