我遇到 CORS 錯誤問題。我確實請求 Google oAuth2,但收到 CORS 錯誤:我想獲得 google 身份驗證并生成 JWT 令牌。當我在不使用客戶端的情況下執行此操作時,一切都很好。當我發送角度請求時,這是 CORS 的問題。我允許所有類型的 CORS。為什么我會收到此錯誤?Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=1020159669873-d9r35ssmnejud852bam87d8gqtcj5qf1.apps.googleusercontent.com&scope=openid%20profile%20email&state=8nizHP1X2z9sA8m0vqM4Lzd6VT24R15eSw5flteTywM%3D&redirect_uri=http://localhost:8080/oauth2/callback/google' (redirected from 'http://localhost:8080/oauth2/authorization/google')from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.Cross-Origin Read Blocking (CORB) blocked cross-origin response https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=1020159669873-d9r35ssmnejud852bam87d8gqtcj5qf1.apps.googleusercontent.com&scope=openid%20profile%20email&state=8nizHP1X2z9sA8m0vqM4Lzd6VT24R15eSw5flteTywM%3D&redirect_uri=http://localhost:8080/oauth2/callback/google with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.我的角度請求: googleLogin(): Observable<LoginResponse> { return this.http.get<LoginResponse> (environment.baseUrl + '/oauth2/authorization/google') .pipe(tap(response => { localStorage.setItem('access_token', response.accessToken); })); }//...public onGoogleLogin(): void { this.authService.googleLogin().subscribe(); }//...跨域資源配置: @Override public void addCorsMappings(CorsRegistry registry) { registry .addMapping("/**") .allowedOrigins("*") .allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE") .maxAge(MAX_AGE_SECS); }
1 回答

aluckdog
TA貢獻1847條經驗 獲得超7個贊
您無法在此示例中獲取令牌,因為您需要進行實際的重定向。有幾種方法可以規避此要求,RFC https://www.rfc-editor.org/rfc/rfc6749#section-1.2中有詳細說明
在彈出窗口中啟動授權流程,并通過瀏覽器中提供的 API 將服務器收到的令牌
postMessage()
從彈出窗口傳回 Web 應用程序。保存狀態,無論狀態是什么,重定向到將啟動授權流程的服務器,并在將令牌交換為授權后,使用令牌作為查詢字符串參數重定向回 Web 應用程序。然后使用它并恢復狀態。
添加回答
舉報
0/150
提交
取消