【发布时间】:2014-01-31 11:07:00
【问题描述】:
使用 3.2 版的 spring-webmvc 和 spring-security-web,我想根据用户角色(或用户是否经过身份验证)返回不同的视图与否),因此对于 "/" 请求,角色 ANONYMOUS 的用户(或未经过身份验证的用户)获得 welcome 页面和角色 USER 获取 主页 页面。
我目前的方法是使用常规控制器:
@Controller
public class WelcomeCtrl {
@RequestMapping("/")
public String welcome(Principal principal) {
if (userAuthenticated(principal)) {
return "redirect:home";
}
return "welcome";
}
private boolean userAuthenticated(Principal principal) {
return principal != null && principal instanceof Authentication
&& hasUserRole((Authentication) principal);
}
private boolean hasUserRole(Authentication principal) {
Collection<? extends GrantedAuthority> authorities = (principal)
.getAuthorities();
return Iterables.contains(Collections2.transform(authorities,
new Function<GrantedAuthority, String>() {
@Override
public String apply(GrantedAuthority authority) {
return authority.getAuthority();
}
}), "ROLE_USER");
}
}
但是,我不是很喜欢它,因为我觉得这个重定向应该用 spring security 来完成(我错了吗?)。您知道使用 Spring Security 配置执行此操作的任何方法吗?我目前的配置如下:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/welcome").permitAll()
.anyRequest().authenticated()
.and().formLogin()
.defaultSuccessUrl("/home").permitAll()
.and().logout().permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder authManagerBuilder)
throws Exception {
authManagerBuilder.inMemoryAuthentication().withUser("user")
.password("password").roles("USER");
}
}
【问题讨论】:
标签: java spring spring-mvc spring-security