如何为Swagger生成的TypeScript Fetch客户端全局添加JWT Token请求头
问题:Swagger生成的TypeScript Fetch客户端自动携带JWT Token
我有一个集成Swagger的Spring Boot应用,通过Swagger Editor生成了TypeScript Fetch客户端,需要实现登录后所有请求自动在请求头携带Bearer Token,但配置后请求仍未携带Token,返回403权限拒绝。
已尝试的方案
1. 登录端点代码
authController().loginUsingPOST(account,'') .then((res: any)=>{ // const ceva = res.clone().json() if(res.token !== undefined && res.token !== null ){ dispatch( setToken(res.token.toString())); //setToken(res.token.toString()); history.push({ pathname: '/', }) } })
2. 网上找到的配置方案(不适用)
private configuration = () => { const openapiConfig = new Configuration(); openapiConfig.baseOptions = { headers: { Authorization: 'Bearer ' + this.accessToken() }, }; return openapiConfig; };
但我生成的configuration.ts中没有baseOptions字段,代码如下:
export interface ConfigurationParameters { apiKey?: string | ((name: string) => string); username?: string; password?: string; accessToken?: string | ((name: string, scopes?: string[]) => string); basePath?: string; } export class Configuration { /** * parameter for apiKey security * @param name security name * @memberof Configuration */ apiKey?: string | ((name: string) => string); /** * parameter for basic security * * @type {string} * @memberof Configuration */ username?: string; /** * parameter for basic security * * @type {string} * @memberof Configuration */ password?: string; /** * parameter for oauth2 security * @param name security name * @param scopes oauth2 scope * @memberof Configuration */ accessToken?: string | ((name: string, scopes?: string[]) => string); /** * override base path * * @type {string} * @memberof Configuration */ basePath?: string; constructor(param: ConfigurationParameters = {}) { this.apiKey = param.apiKey; this.username = param.username; this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; } }
3. 尝试accessToken配置无效
我尝试通过accessToken字段配置,但请求仍未携带Token,代码如下:
export const setToken = createAsyncThunk( 'user/setToken', async (token: string | undefined, { dispatch }) => { localStorage.setItem(KEY_TOKEN, token ?? ''); [setDefaultConfig].forEach((x) => { x((conf) => ({ accessToken: token === undefined ? undefined : `Bearer ${token}`, })); }); return token; }, );
解决方案
1. 修正accessToken赋值逻辑
你生成的客户端是基于OAuth2安全方案设计的,accessToken字段仅需传入Token本身,客户端会自动添加Bearer 前缀,不需要手动拼接:
export const setToken = createAsyncThunk( 'user/setToken', async (token: string | undefined, { dispatch }) => { localStorage.setItem(KEY_TOKEN, token ?? ''); [setDefaultConfig].forEach((x) => { x((conf) => ({ accessToken: token, // 仅传入Token字符串,去掉Bearer前缀 })); }); return token; }, );
2. 匹配Swagger规范的安全方案类型
如果上述方法无效,检查你的Spring Boot Swagger配置中定义的安全方案类型:
- 若使用的是API Key类型(直接通过Header传递Token):
对应的Spring Boot Swagger配置示例:// 修改为apiKey配置,此时需要手动添加Bearer前缀 [setDefaultConfig].forEach((x) => { x((conf) => ({ apiKey: () => `Bearer ${token}`, })); });@Bean public Docket api() { return new Docket(DocumentationType.OAS_30) .securitySchemes(List.of(new ApiKey("JWT", "Authorization", "header"))) .securityContexts(List.of(SecurityContext.builder() .securityReferences(List.of(SecurityReference.builder() .reference("JWT") .scopes(new AuthorizationScope[0]) .build())) .build())); }
3. 手动添加请求拦截(备选方案)
如果重新生成客户端会覆盖配置,可直接修改生成的API客户端代码,统一添加Authorization头(注意:后续重新生成客户端时需重新修改):
// 示例:修改生成的请求函数,添加Token头 async function someApiCall(params: any, options?: any) { const localVarPath = `/api/xxx`; const localVarUrlObj = new URL(localVarPath, basePath); const token = localStorage.getItem(KEY_TOKEN); const localVarRequestOptions: RequestInit = { method: 'GET', headers: { 'Content-Type': 'application/json', ...(options?.headers), ...(token && { 'Authorization': `Bearer ${token}` }) }, }; // 原有请求逻辑... }
内容的提问来源于stack exchange,提问作者antonia simionescu
相关产品推荐
相关产品推荐

