2016-06-23 140 views
1

我正在使用Spring Boot Security通過LDAP爲應用程序對用戶進行身份驗證。默認情況下,此配置將未經授權的用戶重定向到登錄頁面。我想調整此配置以實現兩件事情:Spring Boot安全性403重定向

  1. 重定向嘗試訪問單頁應用程序(在「/」)登錄的未經驗證的用戶。這已經適用於默認行爲。
  2. 對於api調用(「/ api/v1/...」),我想返回403錯誤消息而不是重定向。

我該怎麼做?我看到了一些其他問題給我提示,但我仍然無法弄清楚。

這篇文章的頂部答案似乎相關,但他鏈接到這樣做的XML方法。我想用Java來做。 Spring Security - need 403 error, not redirect

任何幫助將不勝感激!

這裏是我的當前設置:

WebSecurityConfig.java

@Override 
protected void configure(HttpSecurity http) throws Exception { 

    http 
     .authorizeRequests() 
     .antMatchers("/css/**").permitAll() 
     .anyRequest().authenticated(); 
    http 
     .formLogin() 
      .loginPage("/login") 
      .defaultSuccessUrl("/", true) 
      .permitAll() 
      .and() 
     .httpBasic() 
      .and() 
     .csrf().disable() 
     .logout() 
      .logoutSuccessUrl("/login"); 

} 

回答

1

發現,似乎工作的解決方案(到目前爲止,至少)

@Bean 
public AuthenticationEntryPoint delegatingEntryPoint() { 
    final LinkedHashMap<RequestMatcher, AuthenticationEntryPoint> map = new LinkedHashMap(); 
    map.put(new AntPathRequestMatcher("/"), new LoginUrlAuthenticationEntryPoint("/login")); 
    map.put(new AntPathRequestMatcher("/api_v1/**"), new Http403ForbiddenEntryPoint()); 

    final DelegatingAuthenticationEntryPoint entryPoint = new DelegatingAuthenticationEntryPoint(map); 
    entryPoint.setDefaultEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")); 

    return entryPoint; 
} 

@Override 
protected void configure(HttpSecurity http) throws Exception { 

    //delegates based on url (api vs root) 
    http.exceptionHandling().authenticationEntryPoint(delegatingEntryPoint()); 

    http 
     .authorizeRequests() 
     .antMatchers("/css/**").permitAll() 
     .anyRequest().authenticated(); 
    http 
     .formLogin() 
      .loginPage("/login") 
      .defaultSuccessUrl("/", true) 
      .permitAll() 
      .and() 
     .httpBasic() 
      .and() 
     .csrf().disable() 
     .logout() 
      .logoutSuccessUrl("/login"); 
} 

希望這可以幫助別人下來路。我知道我花了很長時間才找到答案。 :)

+0

我認爲,而不是使用Http403ForbiddenEntryPoint,使用HttpStatusEntryPoint與401(未經授權)的狀態代碼是一個更好的選擇。 – xSNRG