【发布时间】:2018-01-24 08:20:06
【问题描述】:
我正在使用 Spring security 和 Thymeleaf 开发我的项目。我有基本的 Spring Security 集成。
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);
}
}
在我的项目中,我有三个角色:学生、教授和管理员。 我想要实现的是当我的学生登录时,他被重定向到页面 indexUser.html。当我的教授登录时,他被重定向到 indexProfesor.html,当管理员登录时,他登陆 indexAdmin.html 页面。
我想到了这样的事情
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
}
但我不知道整个控制器应该是什么样子。
让我的 homeContorller 看起来像这样:
@Controller
public class HomeController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(Model model) {
return "login";
}
}
我也将此代码添加到我的 index.html 中
<span sec:authorize="isAuthenticated()">
<span sec:authentication="name"></span>
| Roles: <span sec:authentication="principal.authorities"></span> |
所以我熟悉登录用户的角色。 这也是我的 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>
【问题讨论】:
标签: spring spring-boot spring-security thymeleaf