如何在angular-oauth2-oidc中避免URL携带state与scope参数?
解决angular-oauth2-oidc请求URL中移除state和scope参数的问题
方法一:修改AuthConfig基础配置
先尝试直接调整AuthConfig参数,看能否阻止库自动添加这两个参数:
export const authConfigDefaults: AuthConfig = Object.freeze({ oidc: false, responseType: 'code', scope: '', // 清空scope参数 strictDiscoveryDocumentValidation: false, redirectUri: redirectURL, silentRefreshTimeout: HALF_HOUR, fallbackAccessTokenExpirationTimeInSec: HALF_HOUR, useSilentRefresh: true, state: '' // 尝试清空state(部分版本中可能无效) });
注:
state是库默认用于CSRF防护的字段,即使设为空,部分场景下仍会自动生成随机值,这种情况需要用后续方法处理。
方法二:使用HTTP拦截器修改请求URL
如果基础配置无效,通过Angular的HTTP拦截器拦截授权请求,手动移除state和scope参数:
- 创建拦截器文件
auth-request.interceptor.ts:
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable() export class AuthRequestInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // 匹配身份服务器的授权端点URL,替换为实际地址 if (req.url.includes('https://你的身份服务器域名/授权端点路径')) { // 复制请求并移除指定参数 const modifiedRequest = req.clone({ params: req.params.delete('state').delete('scope') }); return next.handle(modifiedRequest); } return next.handle(req); } }
- 在
AppModule中注册拦截器:
import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { AuthRequestInterceptor } from './auth-request.interceptor'; @NgModule({ // ...其他模块配置 providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthRequestInterceptor, multi: true } ] }) export class AppModule { }
方法三:手动构建授权URL(最可控)
完全绕过库的默认授权流程,自己构建符合要求的URL并跳转:
import { Component } from '@angular/core'; import { authConfigDefaults } from './auth-config'; @Component({ selector: 'app-login', templateUrl: './login.component.html' }) export class LoginComponent { private authServerEndpoint = 'https://你的身份服务器域名/授权端点路径'; login() { // 手动拼接仅包含必要参数的授权URL const authUrl = `${this.authServerEndpoint}?app=xxx&response_type=code&client_id=${authConfigDefaults.clientId}&redirect_uri=${encodeURIComponent(authConfigDefaults.redirectUri)}`; // 跳转到身份服务器授权页面 window.location.href = authUrl; } }
内容的提问来源于stack exchange,提问作者RagaSGNur
相关产品推荐
相关产品推荐

