【问题标题】:Spring Boot 1.3 Oauth2 Sso return 401 instead of redirect to authorization serverSpring Boot 1.3 Oauth2 Sso 返回 401 而不是重定向到授权服务器
【发布时间】:2016-02-28 10:38:38
【问题描述】:

在 Spring Boot 1.3 中,Spring Boot 中有 Oauth2 的自动配置。

有一个spring guide 提供了一些很好的例子,但我想实现一个不同的解决方案。 我的问题基于提供的click 示例。 我想在访问“/login”端点后被重定向到授权服务器。如果我请求未经身份验证的受保护资源,我希望获得 401(未授权)而不是即时重定向(302)到授权 uri。

这是点击示例的Java代码

@SpringBootApplication
@EnableOAuth2Sso
@RestController
public class SocialApplication extends WebSecurityConfigurerAdapter {

  @RequestMapping("/user")
  public Principal user(Principal principal) {
    return principal;
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/**")
        .authorizeRequests()
        .antMatchers("/", "/login**", "/webjars/**")
        .permitAll()
        .anyRequest()
        .authenticated();
  }

  public static void main(String[] args) {
    SpringApplication.run(SocialApplication.class, args);
  }

}

我尝试添加一个自定义的 AuthenticationEntryPoint,但似乎这被忽略了:(

我尝试了什么:

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/**")
        .authorizeRequests()
        .antMatchers("/", "/login**", "/webjars/**")
        .permitAll()
        .anyRequest()
        .authenticated()
        .and()
        .exceptionHandling()
        .authenticationEntryPoint(new Http401AuthenticationEntryPoint("Session realm=\"JSESSIONID\""));
  }

点击示例的完整源代码可以在github找到。

是否可以实现 401 而不是重定向?

【问题讨论】:

  • 我不明白,你想为所有资源实现 401 错误吗?或者您需要一些带有 401 的页面和另一个带有重定向的页面?
  • 401 在除 /login 之外的所有资源上。 /login 应该重定向到授权服务器

标签: java spring spring-security spring-boot spring-security-oauth2


【解决方案1】:

在 spring-boot 1.3.0 之前,由于在使用此组合时应用自定义配置器的顺序存在问题,这是不可能的(请参阅#4629 for further resolution)。

从 spring-boot 1.3.1 开始,请求标头 X-Requested-With: XMLHttpRequest 表明调用者更喜欢 401 Unauthorized 而不是 302 Found

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 2019-08-09
    • 2015-03-31
    • 2018-08-29
    • 2016-02-01
    • 2016-09-06
    相关资源
    最近更新 更多