We have this currently:
OAuthFlow oAuthFlow = new OAuthFlow();
return new OpenAPI()
.info(new Info().title("Flexx Portal").version("1.0.0"))
// Components section defines Security Scheme "mySecretHeader"
.components(new Components()
.addSecuritySchemes("Authorization", new SecurityScheme()
.type(SecurityScheme.Type.APIKEY)
.in(SecurityScheme.In.HEADER)
.scheme("bearer").bearerFormat("JWT")
.name("Authorization")
.flows(new OAuthFlows().authorizationCode(oAuthFlow))))
.addSecurityItem(new SecurityRequirement().addList("Authorization"));
And we have the Authorize button on swagger.
Is there any way to have this field filled out automatically? By using an env var or something in a local file?
Note that this part of the code is only in dev, not in production :)
So after a long time of digging, I found that you can't add it to the default plug in.
You can easily add it to your project however! This was the least 'hacky' way to do this, and also seemed to be the most secure.
Note that we have swagger completely disabled for production env.
So in your resources folder in springboot add the files below. You can get the swagger-ui-bundle and standalone on their public repo. Same with the css file and html file. The generateToken file is a custom file we have for generating a new token. The tokenAuth file contains the token and is .gitignored.
Next, you can modify the .html file. In the script tag at the end of the body:
<script>
window.onload = function() {
let authKey = token; // <-- token was imported earlier in the file
const ui = SwaggerUIBundle({
url: "http://localhost:3000/v3/api-docs",
dom_id: '#swagger-ui',
deepLinking: true,
docExpansion: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: SwaggerUIStandalonePreset ? "StandaloneLayout" : "BaseLayout",
defaultModelsExpandDepth: -1,
operationsSorter : "method",
persistAuthorization: true,
requestInterceptor(req) {
req.headers['Authorization'] = authKey; // <-- THIS IS WHERE YOU SET AUTH HEADERS
return req
}
});
};
</script>
Basically this will set the headers on each request. This makes working with the api far easier. Specially since our script populates the tokenAuth.js file automatically, so if a token expires, it's far easier to run the script for us, compared to getting a token and pasting it into the Authorization Token Box every time we restart our program.
This is also really nice for any other further swagger customizations you want to make!