我正在使用 Spring Boot Security 通过 LDAP 对应用程序的用户进行身份验证。默认情况下,此配置会将未经授权的用户重定向到登录页面。我想调整此配置以实现两件事:
- 将尝试访问单页应用程序(位于“/”)的未经身份验证的用户重定向到登录。这已经适用于默认行为。
- 对于 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");
}
最佳答案
找到了一个似乎有效的解决方案(到目前为止,至少)
@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");
}
希望这对以后的人有所帮助。我知道我花了很长时间才找到答案。 :)
关于java - Spring Boot 安全 403 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37999884/