I want to set preauthorizeApiKey in swagger-ui-react application auto authorized

Viewed 758

I have below code where I have set preauthorizeApiKey and it's working fine and calls to APIs is also working. APIs need header "Authorization: Bearer xxxxxxxxxxx". I had key stored in react store and reading using getToken().

import React from 'react';
import SwaggerUI from 'swagger-ui-react';
import swaggerSpec from '../../swagger.json';
import { getToken } from '../../api/utils'

export const complete=function(swaggerUi)
{
  let token = getToken();
  swaggerUi.preauthorizeApiKey('bearerAuth',  token.Token);
}

const ApiDocs = () => {
  return <SwaggerUI spec={swaggerSpec} onComplete={(swaggerUi) => complete(swaggerUi)} />
};

export default ApiDocs;

Below is my route configuration:

<Route path="/api-docs" component={ApiDocs} />

I don't need to click on Authorize button on swagger UI screen and it is auto Authorized. Just wanted to share for any comment/suggestion/improvement.

1 Answers

The onComplete props should be a function. Please see the document here.

import React from "react";
import SwaggerUI from "swagger-ui-react";
import swaggerSpec from "../../swagger.json";
import { getToken } from "../../api/utils";

export const complete = function (swaggerUi) {
  const token = getToken();
  swaggerUi.preauthorizeApiKey("bearerAuth", token.Token);
};

const ApiDocs = () => {
  return <SwaggerUI spec={swaggerSpec} onComplete={complete} />;
};

export default ApiDocs;
Related