![](/img/trans.png)
[英]Spring Security Java Configuration IS_AUTHENTICATED_FULLY
[英]Spring Security Java configuration for authenticated users with a role
我正在嘗試使用Spring Boot使用Java配置來配置Spring Security。
我的WebSecurityConfig類有一個這樣的配置方法
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/login", "/css/**", "/js/**", "/img/**", "/bootstrap/**" ).permitAll()
.antMatchers("/individual", "/application", "/upload").hasRole("USER")
.and()
.formLogin()
.loginPage("/login")
.successHandler(successHandler);
}
我為未經身份驗證的用戶提供了登錄頁面,並且用戶進行了身份驗證。 但是,當嘗試訪問url /個人時,我得到403錯誤,這在日志中
2015-11-12 13:59:46.373 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/individual'; against '/'
2015-11-12 13:59:46.373 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/individual'; against '/login'
2015-11-12 13:59:46.373 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/individual'; against '/css/**'
2015-11-12 13:59:46.373 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/individual'; against '/js/**'
2015-11-12 13:59:46.374 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/individual'; against '/img/**'
2015-11-12 13:59:46.374 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/individual'; against '/bootstrap/**'
2015-11-12 13:59:46.374 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/individual'; against '/individual'
2015-11-12 13:59:46.374 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /individual; Attributes: [hasRole('ROLE_USER')]
2015-11-12 13:59:46.374 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@4c2eda81: Principal: org.springframework.security.core.userdetails.User@4c0ab982: Username: foo@bar.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffc7f0c: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 6E0BF830C070912EAC0050D1285D5CF9; Granted Authorities: USER
2015-11-12 13:59:46.374 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@6f192fd7, returned: -1
2015-11-12 13:59:46.386 DEBUG 34468 --- [nio-8090-exec-6] o.s.s.w.a.ExceptionTranslationFilter : Access is denied (user is not anonymous); delegating to AccessDeniedHandler
如果我更換.hasRole("USER")
與.authenticated()
它的工作原理和用戶獲取所需的頁面,但沒有一個角色被檢查。
我無法弄清楚如何指定用戶必須經過身份驗證並具有USER角色。 我看了很多例子並嘗試了很多組合,但是我無法按照需要使用它。 大多數示例也引用了較舊的基於XML的配置,我想避免這些配置。
如何指定可以使用具有特定角色的經過身份驗證的用戶訪問某些URL模式,我需要做什么?
根據要求,成功處理程序方法如下所示
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth)
throws IOException, ServletException {
// Here we want to check whether the user has already started the process and redirect to the appropriate stage
log.info("User {} has been authenticated", auth.getName());
if(auth.getName().equals("foo@bar.com"))
{
redirectStrategy.sendRedirect(request, response, "/individual");
return;
}
redirectStrategy.sendRedirect(request, response, "/application");
}
請注意,根據代碼中的注釋,這是早期的WIP。 我知道這有效,因為日志消息出現,並且在WebSecurity類中沒有角色檢查所提供的頁面。
編輯:注意到在提到roleService.getDefaultRole()的問題中的拼寫錯誤。 這是一個錯誤,並已得到糾正。
我認為您登錄的用戶foo@bar.com設置了錯誤的權限。 在日志中,您可以看到權限是['USER'],但由於您正在使用角色,因此它應該是['ROLE_USER']。 您在哪里定義foo@bar.com的權限?
否則嘗試切換
.antMatchers("/individual", "/application", "/upload").hasRole("USER")
至
.antMatchers("/individual", "/application", "/upload").hasAuthority("USER")
我已經解決了我自己的問題,部分歸功於這里的各種建議讓我以不同的方式進行研究。 還注意到FrontierPsychiatrist也提供了答案,但在我開展工作時我沒有發現響應。
問題在於Spring可以互換地提到ROLES和AUTHORITIES。
實現UserDetailsService
接口以允許Spring從應用程序數據庫加載用戶記錄后,我創建了org.springframework.security.core.userdetails.User
的實例並設置了授予的權限 。 在日志語句中可以看到User對象具有 - Granted Authorities: USER
,但是我的安全配置正在檢查角色,並且失敗。 簡單來說,解決方案是檢查權限。 我還清理了配置,將要忽略的URL模式與身份驗證和授權分開。 完整的代碼片段如下
@Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers( "/css/**", "/js/**", "/img/**", "/bootstrap/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/individual","/application", "/upload").hasAuthority("USER")
.and()
.formLogin()
.loginPage("/login")
.successHandler(successHandler)
.permitAll()
.and()
.logout()
.deleteCookies("remove")
.logoutSuccessUrl("/login?logout")
.permitAll();
}
在Spring 4 MVC中使用基於Java的配置時,我真的希望這有助於其他人。
修改您的配置是這樣的。
http.authorizeRequests().antMatchers("/individual","/application", "/upload")
.hasRole("USER").and().authorizeRequests().anyRequest()
.authenticated().and()
.formLogin()
.loginPage("/login")
.successHandler(successHandler);
如果您不希望對所有請求進行身份驗證,則可以使用anyRequest()
替換anyRequest()
方法antMatchers("/urls-goes-here")
這是一個教程,可以幫助您實現以下目標:
http://www.jcombat.com/spring/custom-authentication-success-handler-with-spring-security
我猜你忘了在你的處理程序中設置會話屬性:
HttpSession session = request.getSession();
session.setAttribute("uname", authUser.getUsername());
session.setAttribute("authorities", authentication.getAuthorities());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.