如何将 jwt 令牌添加到 swagger 生成的获取打字稿客户端的所有请求标头?

问题描述 投票:0回答:1

我在 Spring boot 中有一个具有 swagger 的应用程序,我从中生成了一个打字稿获取客户端 https://editor-next.swagger.io/。我想知道如何使用 jwt,我更感兴趣的是如何在登录后使所有请求标头都具有不记名令牌。

我尝试过这个解决方案:

登录端点:

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: '/',
          })
        }
      })

还在互联网上找到了这个解决方案:

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;
    }
}

我尝试了这样的方法,但它仍然不起作用,因为请求不包含标头令牌,并且我被禁止了。

这是我用 accessToken 尝试过的:

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;
    },
  );
reactjs fetch swagger token bearer-token
1个回答
0
投票

经过一番痛苦的调试,我设法让它工作:

const customFetch: WindowOrWorkerGlobalScope['fetch'] = async (input: RequestInfo, init?: RequestInit) => {
  // Add your custom headers here
  const customHeaders = {
    'Authorization': {GET AND INSERT TOKEN HERE}
  };

  if (init && init.headers) {
    init.headers = new Headers(init.headers);
    Object.entries(customHeaders).forEach(([key, value]) => {
      (init.headers as Headers).append(key, value);
    });
  } else {
    init = { ...init, headers: customHeaders };
  }

  return fetch(input, init);
};

稍后定义配置时,需要将其指定为

fetchApi
:

const configuration = new Configuration({
      basePath: 'https://yourendpoi.nt',
      fetchApi: customFetch
    });
© www.soinside.com 2019 - 2024. All rights reserved.