簡體   English   中英

Spring Security OAuth 2.0 Google:在未經授權的請求后重定向到默認 URL 而不是請求的 URL

[英]Spring Security OAuth 2.0 Google: redirect to default URL after unauthorized request instead of requested URL

我使用 Spring Security OAuth 2.0 和 Google 作為身份提供者。 我在正確處理會話超時和重新身份驗證方面遇到問題。

設想:

  • 會話超時后對 REST API 的一些請求。
  • 前端處理 HTTP 403 並顯示帶有 Spring Security 登錄端點鏈接的屏幕。
  • 用戶點擊此鏈接。 Spring 問題會使用必要的參數(代碼、狀態等)重定向到 Google 登錄頁面。 用戶成功重新認證。

當前行為:

  • 登錄后,Google 重定向到先前請求的 REST API URL。 結果用戶在瀏覽器中看到了一些 JSON。 我只是不明白應用程序的哪個部分可以保存它。 我禁用了一切。 (請參閱配置類下面的注釋。)

期望的行為:

  • 登錄后谷歌重定向到一些起始 UI 屏幕。

我的配置類:

import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.web.authentication.Http403ForbiddenEntryPoint
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler

@Configuration
@EnableWebSecurity
class WebSecurityConfiguration: WebSecurityConfigurerAdapter() {

    @Value("\${app.security.oauth2.defaultSuccessUrl}")
    lateinit var defaultSuccessUrl: String

    @Throws(Exception::class)
    override fun configure(httpSecurity: HttpSecurity) {
        val successHandler = SimpleUrlAuthenticationSuccessHandler()
        successHandler.setUseReferer(false)
        httpSecurity
            .antMatcher("/**")
            .authorizeRequests()
            .antMatchers("/", "/login**", "/js/**", "/error**").permitAll()
            .anyRequest().authenticated()
            .and().oauth2Login()
            .successHandler(successHandler)
            .defaultSuccessUrl(defaultSuccessUrl)
            .and().logout().logoutSuccessUrl("/login").deleteCookies("JSESSIONID").permitAll()
            .and()
            .csrf().disable()
            .exceptionHandling()
            .authenticationEntryPoint(Http403ForbiddenEntryPoint())
    }

}
  • defaultSuccessUrl設置為所需的 UI 屏幕。
  • 我已經將成功處理程序更改為SimpleUrlAuthenticationSuccessHandler而不是SavedRequestAwareAuthenticationSuccessHandler以關閉 Spring 保存請求的 URL。
  • successHandler.setUseReferer(false)在 HTTP 級別禁用Referer標頭。
  • 我正在使用Http403ForbiddenEntryPoint()在會話超時時發出 HTTP 403。 前端處理這個並顯示帶有 Spring Security 登錄 URL 鏈接的登錄屏幕。

我做錯了什么?

提前致謝。

設置defaultSuccessUrl將覆蓋您的successHandler() ,因為設置 URL 實際上會添加您想要替換的SavedRequestAwareAuthenticationSuccessHandler 順序很重要,因為oauth2Login配置器中只有一個successHandler

相反,您需要將defaultSuccessUrl傳遞給SimpleUrlAuthenticationSuccessHandler的構造函數,並且只設置successHandler(successHandler)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM