使用彈簧webmvc和3.2版彈簧安全的web視圖築底,我想返回根據用戶角色的不同觀點(或者是否用戶進行身份驗證或沒有),所以,對於"/"
請求角色匿名(或不經過身份驗證的用戶的用戶)獲取歡迎頁和作用用戶的用戶得到家頁。春季3.2:選擇用戶角色
我目前的做法與常規控制器這樣做:
@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");
}
}
@Macias你對我的答案滿意嗎,對你來說看起來不錯,我的朋友 – Tenacious
@Macias如果它看起來不錯,請注意它,所以它會對其他人有所幫助我的朋友 – Tenacious
那麼,從春季文檔複製粘貼的確切位置是我的問題的答案? -1爲我的朋友 – macias