How to send Authorization header with a request in swagger-ui-react?

断了今生、忘了曾经 提交于 2021-01-27 11:41:19

问题


I use swagger-ui-react in my application. But I don't know how to config to add the authorization into api requests.

I had found an answer use in swagger ui from here:

window.swaggerUi = new SwaggerUi({...})
...
swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", "Basic dXNlcm5hbWU6cGFzc3dvcmQ=", "header"));

But I don't know how to use in swagger-ui-react. Here is my code:

import styles from './index.less';

import React from 'react';
// tslint:disable
import SwaggerUI from 'swagger-ui-react';
import 'swagger-ui-react/swagger-ui.css';
// tslint:able

const SwaggerComp = params => {
    const auth = params.authorization;
    return (
        <div className={styles.wrapper}>
         <SwaggerUI
           url="/v2/swagger-file-url"
           withCredentials
         />
       </div>
    )
};

export default SwaggerComp;

回答1:


To send the Authorization header in "try it out" requests, your API definition file (/v2/swagger-file-url) must define the appropriate security for operations. Users will need to click the "Authorize" button to enter the authentication information (such as the username and password for Basic auth) before doing "try it out".

OpenAPI 3.0 example:

openapi: 3.0.2

components:
  securitySchemes:
    basicAuth:
      type: http
      scheme: basic

security:
  - basicAuth: []

OpenAPI 2.0 example:

swagger: '2.0'

securityDefinitions:
  basicAuth:
    type: basic

security:
  - basicAuth: []

For more information, see:

  • Authentication guide for OpenAPI 3.0
  • Authentication guide for OpenAPI 2.0



回答2:


In react-swagger-ui, they have a network property called requestInterceptor, in here you can modify the request json before passing it to the api call, so you can add the authorization header in there, and remember to return the modified json in requestInterceptor.

To set up the authentication header in the json, there are a couple ways to do it, I was using sigv4 for authorization header, and I used Amplify Signer to generator all the required header(Authorization, X-Amz-Date..) for me before the api call, this is the link here.



来源:https://stackoverflow.com/questions/57769012/how-to-send-authorization-header-with-a-request-in-swagger-ui-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!