title: Spring security role access, log in
body: <p>I am having some issues implementing spring security, in particular the roles USER and ADMIN. I want each role type to redirected to its respective page /user and /admin. I have read countless tutorials and each one seems to be a little different than the last one and it's all very confusing. I was wondering if someone could define what I need to do as I dont think I am too far off with what I have done so far. The issue at the moment is that It does not redirect as per say, I do not think it's creating a session as when I try to retrieve any Prinicipal.getName() after login its always null. Is there anything other than this I am missing? Any help is greatly appreciated.</p>
  
  <p>Pretty much the whole application bar the register feature, userRepo and views.</p>
  
  <p><strong>public class UserDetailService implements UserDetailsService {</strong></p>
  
  <pre><code>@Autowired
  UserRepo userRepo;
  
  public UserDetailService(UserRepo userRepo){
      this.userRepo=userRepo;
  }
  
  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  
      //Find a user by username
      User user = this.userRepo.findByUsername(username);
  
      //Check if it's null
      if(user == null) throw new UsernameNotFoundException(username);
      //if not then return user detail with arguments
      else return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), getAuthorities(user));
  }
  
  @SuppressWarnings("serial")
  public static Collection&lt;GrantedAuthority&gt; getAuthorities(User user) {
      // make everyone ROLE_USER
      Collection&lt;GrantedAuthority&gt; grantedAuthorities = new ArrayList&lt;GrantedAuthority&gt;();
      GrantedAuthority grantedAuthority = new GrantedAuthority() {
  
          @Override
          public String getAuthority() {
              if (user.getRole().equals("ROLE_USER")) return "ROLE_USER"; 
              else return "ROLE_ADMIN";
          }
      };
      grantedAuthorities.add(grantedAuthority);
  
      grantedAuthority = new GrantedAuthority() {
  
          @Override
          public String getAuthority() {
              return "ROLE_USER";
          }
      };
      grantedAuthorities.add(grantedAuthority);
      return grantedAuthorities;
  }
  </code></pre>
  
  <p><strong>@Service
  public class UserServices  {</strong></p>
  
  <pre><code>@Autowired
  private UserRepo userRepo;
  
  //User register service
  public void register(User user) {       
      //Encrypt password
      user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
      user.setRole("ROLE_USER");
      this.userRepo.save(user);               
  }
  
  //Used to add admin accounts on boot
  public void adminOnBoot(User user) {
      user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
      this.userRepo.save(user);
  }
  
  //Return the list of users available
  public List&lt;User&gt; getAllUsers() {
      return this.userRepo.findAll();     
  }
  
  //Check if user exists by a username
  public Boolean existsByUsername(String username) {
      return this.userRepo.existsByUsername(username);
  }
  
  //Check if user exists by an email
  public Boolean existsByEmail(String emailAddress) {
      return this.userRepo.existsByEmail(emailAddress);
  }
  
  //Login user by the login forms username and password
  public User loginUserByForm(LoginForm loginForm) {      
      User user = this.userRepo.findByUsername(loginForm.getUsername());      
      if(user != null &amp;&amp; BCrypt.checkpw(loginForm.getPassword(), user.getPassword()))
          return user;
  
      else return null;
  }
  </code></pre>
  
  <p><strong>@Controller
  public class LoginController {</strong></p>
  
  <pre><code>@Autowired
  private UserServices userService;
  
  //LOGIN PROCESS - NO NEED FOR SEPERATE VIEW
  @RequestMapping(value = "/login", method = RequestMethod.POST)
  public String verifyLogin(@Valid @ModelAttribute("loginForm") LoginForm loginForm, Model model, HttpServletRequest request) {
  
      User user = userService.loginUserByForm(loginForm);
      if(user == null) {
  
          //Add a model attribute for an error
          model.addAttribute("loginError", "notNull");
  
          //Passing the no. of registered users
          model.addAttribute("users", userService.getAllUsers()); 
          model.addAttribute("userCount", userService.getAllUsers().size()); 
  
          return "index";
      }
  
      //create the HttpSession
      request.getSession().setAttribute("user", user);
  
      //Passing the no. of registered users
      model.addAttribute("users", userService.getAllUsers()); 
      model.addAttribute("userCount", userService.getAllUsers().size()); 
      model.addAttribute("username", user.getUsername()); 
  
      //TO DO
      return "admin";     
  }
  
  @RequestMapping("/logout")
  public String verifyLogout(HttpServletRequest request, HttpServletResponse response) {
  
      Authentication auth = SecurityContextHolder.getContext().getAuthentication();
      if (auth != null){    
          new SecurityContextLogoutHandler().logout(request, response, auth);
      }
      return "redirect:/login?logout";
  
  }
  </code></pre>
  
  <p>}</p>
  
  <p><strong>@Configuration
  @EnableWebSecurity
  public class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter{</strong></p>
  
  <pre><code>@Autowired 
  private UserRepo userRepo;
  @Autowired
  private CustomAuthenticationHandler authHandler;
  
  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      auth.userDetailsService(userDetailsServiceBean());
  }
  
  @Override
  public UserDetailsService userDetailsServiceBean() throws Exception {
      return new UserDetailService(userRepo);
  }
  
  @Override
  protected void configure(HttpSecurity http) throws Exception {
      http
          .authorizeRequests()
               //CSS FILES AND IMAGES
              .antMatchers("/css/**", "/img/**", "/js/**").permitAll()
               //PAGES FOR ALL PEOPLE
              .antMatchers("/", "/login", "/register/**").permitAll()
               //PAGES FOR ADMIN
              .antMatchers("/admin/**").hasAuthority("ADMIN")
               //PAGES FOR USERS
              .antMatchers("/user/**").hasAuthority("USER")
              .anyRequest().authenticated()
          .and()
          .formLogin()
          .loginProcessingUrl("/login")
          .loginPage("/")
          .failureUrl("/?error")
          .and()
          .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/");
      ;
  }
  </code></pre>
  
  <p>}</p>
  
  <p><strong>public class CustomAuthenticationHandler implements AuthenticationSuccessHandler {</strong></p>
  
  <pre><code>@Autowired
  UserRepo userRepo;
  
  @Override
  public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                      Authentication authentication) throws ServletException, IOException {
  
      HttpSession session = request.getSession();
      User user = userRepo.findByUsername(authentication.getName());
  
      session.setAttribute("user", user);
      response.setStatus(HttpServletResponse.SC_OK);
      if (user.getRole().equals("ROLE_ADMIN")) {
          response.sendRedirect("/admin/");
      } else {
          response.sendRedirect("/user/" + user.getUsername());
      }
  }
  </code></pre>
  
  <p>}</p>