Page redirecting depending on Role using Spring security and Thymeleaf - Spring

Viewed 3775

I am working on my project with Spring security and Thymeleaf. I have basic Spring Security integration.

SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private DataSource dataSource;

    @Autowired
      public void configureGlobal (AuthenticationManagerBuilder auth) throws Exception
      {
        auth
          .jdbcAuthentication()
            .dataSource(dataSource);
      }

    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
              .antMatchers("/login").permitAll()
              .antMatchers("/classesTable").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")

                .and()
            .httpBasic();
      } 
}

SecurityWebApplicationInitializer.java

public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer
{
    public SecurityWebApplicationInitializer(){
        super(SecurityConfig.class);
    }

}

In my project I have three roles: student, professor and admin. What I would like to achieve is when my student logs in that he is redirected to page indexUser.html. When my professor logs in he is redirected to indexProfesor.html and when admin does he lands on indexAdmin.html page.

I had in mind something like this

if(role.contains("ROLE_ADMIN")){
      //redirect from here to indexAdmin.html

    }else if(role.contains("ROLE_USER")) {
        //redirect to indexUser.html
    }else
        //redirect to indexProfesor.html
}

But I don't have picture how whole controller should look like.

Have my homeContorller that looks like this:

@Controller
public class HomeController {

   @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginPage(Model model) {
        return "login";
    }
}

Also I added this code to my index.html

<span sec:authorize="isAuthenticated()">
<span sec:authentication="name"></span>
| Roles: <span sec:authentication="principal.authorities"></span> |

So I am familiar with role that my logged user has. Here is also code for my login.html

<form  th:action="@{/login}" method="post" class="l-form">
  <input type="text" name="username"/>
  <input type="password" name="password"/>
  <input type="hidden" th:name="${_csrf.parameterName}" 
   th:value="${_csrf.token}" />

   <button type="submit" class="btn">Sign in!</button>
</form>
3 Answers
Related