java - Spring Boot 安全 403 重定向

标签 java authentication spring-security spring-boot ldap

我正在使用 Spring Boot Security 通过 LDAP 对应用程序的用户进行身份验证。默认情况下,此配置会将未经授权的用户重定向到登录页面。我想调整此配置以实现两件事:

  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");

}

最佳答案

找到了一个似乎有效的解决方案(到目前为止,至少)

@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/

相关文章:

java - 使用 JavaSpaces 的 Blitz 实现

java - Java 中逻辑的分组方式有保证吗?

html - 为什么浏览器不要求记住密码?

java - Spring 安全 : Method Level Security Prevent Access to a Role

rest - 如何在 Spring Boot Web 应用程序中保护 REST API?

java - 在 Java 中获取相同的 CST 和 EST 时间

Java For语句和扫描仪输入

Asp.net 表单例份验证 cookie 不支持 IIS7 超时

session - Laravel 多域 session

java - 使用 PreAuthorize 时,ResponseBody 方法中的 Autowiring 服务为 Null