meimei han
meimei han

Reputation: 61

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

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;

Upvotes: 6

Views: 6517

Answers (2)

Emma Wu
Emma Wu

Reputation: 11

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.

Upvotes: 0

Helen
Helen

Reputation: 98011

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:

Upvotes: 2

Related Questions