[英]Spring Security configure httpsecurity
我正在嘗試Spring Security,但確實陷入了這樣的任務:我有一個默認網頁,該網頁默認是未經身份驗證的,並且我有一批控制器調用,我想用預授權注釋。 基本思想是,我想禁用默認的“重定向到登錄頁面”,但仍然有機會使用Spring Security的方法安全性復合體。
我使用的是Java配置,如下所示:
@Configuration
@EnableWebSecurity
public class SpringWebSecurityConfig extends WebSecurityConfigurerAdapter{
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/res/**"); // #3
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();
}
}
我知道(或似乎理解)到這一點為止,我所有的電話都應該被允許(過去兩天一直在討論這個問題,並且顯然沒有想法了)。
我想要保護的Controller方法是:
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping(value="/admin", method = RequestMethod.GET)
public String getAdminPage(Model model){
return "admin";
}
我知道我可以使用antMatcher添加“ / ** / admin”並授權對特定url的調用,但是總體思路是:
UPD:基本問題是僅在拒絕訪問的情況下才調用重定向到登錄頁面,從而允許匿名角色用於基本站點視圖和調用。
回答我自己的問題(可能看起來不干凈)。
您可以配置Spring Security Http Security,這樣它就不會要求在每個頁面上登錄:
@Override protected void configure(HttpSecurity http) throws Exception { http.antMatcher("/**").authorizeRequests().anyRequest().permitAll();
要啟用方法安全性(PreAuthorize(“ hasRole('ADMIN')”)等),您需要添加注釋:
@EnableGlobalMethodSecurity(prePostEnabled = true)
之后,您需要向HttpSecurity對象添加一些內容以捕獲“ Access Denied and ect”的異常(在其他一些stackoverflow問題線程上找到此內容):
http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
if (authException != null) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().print("Unauthorizated....");
}
}
});
現在,您可以使用@PreAutherized保護控制器和其他組件。 希望這會幫助某人。
但是仍然存在一件事-當用戶未經授權並且我嘗試訪問某個預授權頁面時,上述異常處理程序將被調用,並返回“ Unauthorized ...”消息。 但是,當用戶獲得授權並且嘗試使用具有不同的preAuthorized角色的頁面時,我將獲得默認的403 Access Denied。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.