尽管成功,Spring Security OAuth2 登录重定向到错误页面

Twi*_*wiN 4 spring spring-security oauth-2.0 spring-boot spring-security-oauth2

为了不泄露机密信息,提供者将被替换$PROVIDER

授权有效,但不是将我重定向到索引,而是将我重定向到/error.

重现步骤

  1. 启动应用程序
  2. 转到任何页面,它会将我重定向到http://localhost/oauth_login显示链接的页面login
  3. 单击链接login(链接到http://localhost/oauth2/authorization/$PROVIDER
  4. 被重定向到 http://localhost/error

错误页面显示以下内容(我对其进行了格式化以提高可读性):

{
    "timestamp":"2018-04-05T14:18:47.720+0000", 
    "status":999, 
    "error":"None", 
    "message":"No message available"
}
Run Code Online (Sandbox Code Playgroud)

这显然与默认Whitelabel Error Page上显示的参数相同,所以实际上,唯一的问题是它是 JSON 格式,除了是一个 HTML 页面。如果我刷新http://localhost/error后,它会显示正常的Whitelabel Error Page

现在这就是奇怪的地方,如果我http://localhost/在被重定向到错误页面后尝试导航到我的身份验证(用户数据在那里,所以授权成功)。基本上,问题是我被重定向到http://localhost/error而不是http://localhost/.

因为它功能齐全(除了重定向),我不会发布整个安全配置,而是将其限制为相关代码:

安全配置

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
            .csrf().disable()
            .authorizeRequests().anyRequest()
                .authenticated()
            .and()
                .oauth2Login()
            .loginPage("/oauth_login")
                .defaultSuccessUrl("/")
                .failureUrl("/oauth_login")
                .permitAll()
            .and()
                .logout()
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/oauth_login").permitAll()
    ;
}
Run Code Online (Sandbox Code Playgroud)

相关属性

spring.security.oauth2.client.registration.$PROVIDER.redirectUriTemplate=http://localhost/login/oauth2/code/$PROVIDER
Run Code Online (Sandbox Code Playgroud)

相关信息

  • 一旦我在网站上通过身份验证,我就可以导航、刷新页面,做任何我想做的事情(直到我退出)。

TL;DR授权有效但重定向到/error而不是/.

Twi*_*wiN 5

我实际上找到了我自己问题的答案,但我还是决定发布它,以防有人遇到同样的问题。

.defaultSuccessUrl("/")
Run Code Online (Sandbox Code Playgroud)

本来应该

.defaultSuccessUrl("/", true)
Run Code Online (Sandbox Code Playgroud)

如果您没有将其设置为true,它会自动将用户重定向到上一个请求,在我的情况下,最后一个请求是向 url 发出的/error,这就解释了我的问题。

通过将其设置为true,您可以强制用户重定向到您所在的defaultSuccessUrl位置。

通过查看日志,您实际上可以看到它:

2018-04-05 11:04:09 DEBUG [-nio-80-exec-10] RequestAwareAuthenticationSuccessHandler : Redirecting to DefaultSavedRequest Url: http://localhost/error
2018-04-05 11:04:09 DEBUG [-nio-80-exec-10] o.s.security.web.DefaultRedirectStrategy : Redirecting to 'http://localhost/error'
Run Code Online (Sandbox Code Playgroud)