Comments (31)
anyway to achieve this using the Token attached to the swagger Authorize button?
from swagger-ui-express.
@scottie1984 i'm not able to authorize token with above codes!!..i'm using swagger-ui-express.
from swagger-ui-express.
Just adding a note here for anyone landing here from the preserve auth token issue above. If you're trying to get your authorization token to persist between refreshes you can use swaggerOptions to pass in a persistAuthorization
value like this:
app.use(
'/api-docs',
swaggerUi.serve,
swaggerUi.setup(swaggerDoc, {
swaggerOptions: {
docExpansions: "none",
persistAuthorization: true
}
})
);
from swagger-ui-express.
I would have to make a change to allow this to work. Looking at the link you provided:
ui.authActions.authorize({JWT: {name: "JWT", schema: {type: "apiKey", in: "header", name: "Authorization", description: ""}, value: "Bearer "}})
I will add a authAction to the custom options and if it is defined I will pass it into the ui.authActions.authorize function. What do you think?
from swagger-ui-express.
Are the security definitions in a components section?
"components": {
"securitySchemes": {
"JWT": {
"description": "",
"type": "apiKey",
"name": "Authorization",
"in": "header"
}
}
}
from swagger-ui-express.
i do this with securityDefinitions
and security
parameters in swagger.js:
const swaggerAutogen = require('swagger-autogen')()
const doc = {
info: {
title: 'Sales Server',
description: 'Documentation API. https://github.com/danielschmitz/sales-server',
version: '1.0',
},
host: 'localhost:3000',
basePath: '/api',
securityDefinitions: {
bearerAuth: {
type: 'apiKey',
name: 'x-auth-token',
scheme: 'bearer',
in: 'header',
},
},
security: [{ bearerAuth: [] }],
}
const outputFile = './src/swagger.json'
const endpointsFiles = [
'./src/api/category.js'
]
swaggerAutogen(outputFile, endpointsFiles, doc)
so a green Authorize buttons appears:
Click in the button, fill token:
from swagger-ui-express.
from swagger-ui-express.
O que funcionou comigo foi o seguinte código no arquivo swagger.json.
Código abaixo logo após a configuração de info:
"swaggerOptions": {
"docExpansions": "none",
"persistAuthorization": true
},
"securityDefinitions": {
"bearerAuth": {
"type": "apiKey",
"name": "x-auth-token",
"scheme": "bearer",
"in": "header"
}
},
Codigo abaixo no final do arquivo:
"components": {
"securitySchemes": {
"bearerAuth": {
"type": "http",
"name": "x-auth-token",
"scheme": "bearer",
"in": "header"
}
}
},
"security": [{ "bearerAuth": [] }]
Espero ter ajudado
from swagger-ui-express.
Yes, it'll be fine for my goals:) Will it a button 'Authorize' like here or as a input field in explorer? Thanks!
from swagger-ui-express.
I have added this, let me know if it works:
const express = require('express');
const app = express();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
var options = {
swaggerOptions: {
authAction :{ JWT: {name: "JWT", schema: {type: "apiKey", in: "header", name: "Authorization", description: ""}, value: "Bearer <JWT>"} }
}
};
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));
from swagger-ui-express.
@scottie1984 Sure! Thank you.
from swagger-ui-express.
@scottie1984 The above code is not working.
var options = JSON.parse(document.getElementById('swagger-options').innerText)
this line remove JWT
from value: "Bearer <JWT>"
It's coming like "{"jwt":{"name":"jwt","schema":{"type":"apiKey","in":"header","name":"Authorization"},"value":"Bearer "}}"
from swagger-ui-express.
@arpit2438735 I believe you have to replace with your auth token
from swagger-ui-express.
@scottie1984 you meant to say hardcoded token? I didn't get what you trying to say, can you explain in more detail.Thanks
from swagger-ui-express.
@arpit2438735 apologies, yes - replace < JWT > with a hardcoded token. Please follow this issue for where the solution can from (and other possible solutions.
from swagger-ui-express.
I just tried to implement this with Basic authentication. This is my code:
basicAuth: {name: "basicAuth", schema: {type: "basic", in: "header", name: "Basic Auth", description: ""}, value: "Basic <base64 encoded user:password combination>"}
It's not working though. The token in the sent request also evaluates to "undefined:undefined". I also tried:
basicAuth: {name: "basicAuth", schema: {type: "basic", in: "header", name: "Basic Auth", description: ""}, value: "Basic <user:password>"}
which gives me the same result.
The generated request looks right, except for the "value" part:
curl -X GET "" -H "accept: application/json" -H "authorization: Basic dW5kZWZpbmVkOnVuZGVmaW5lZA=="
What am I doing wrong?
from swagger-ui-express.
I haven't been able to find a way to do with with Swagger UI. I suggest trying to raise an issue with Swagger UI directly as they will be in a much better position to help. From that if you manage to find something that needs added to this module then I am happy to do so.
from swagger-ui-express.
@scottie1984 Apart from adding the "authAction" property in the "swaggerOptions" object (exactly like above, with my own jwt token), do I need to specify a security schema like the one below? When I use this, the "Try it out" --> "Execute" buttons throw the error below and do not execute any request.
# swagger.yaml
/users: # token protected api
x-swagger-router-controller: userController
get:
summary: Get list of users
description: ""
operationId: getUsers
# some code here ..
security:
- authentication: []
securityDefinitions:
authentication:
type: apiKey
name: Authorization
in: header
Error:
TypeError: o is undefined
Stack trace:
t.default<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:52:83216
p/<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:62:130652
c/<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:62:130385
t.default/</</<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:92:99717
t.default/</<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:92:99671
pe.prototype.withMutations@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:1:34201
t.default/<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:92:99643
p@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:52:210751
v/</</<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:1:60393
r/<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:92:102197
t.validateParams/<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:52:92856
r@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:62:133500
p/<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:62:130652
t/r.onClick@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:62:44606
r@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:38:59584
a@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:38:55670
s@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:38:55887
h@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:12:49327
m@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:12:49455
r@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:52:186344
processEventQueue@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:12:50517
r@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:91:95984
handleTopLevel@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:91:96057
o@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:91:96508
perform@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:12:72177
batchedUpdates@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:91:94764
o@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:12:12315
dispatchEvent@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:91:97363
swagger-ui-bundle.js:62:130704
TypeError: p.forEach is not a function
Stack trace:
i@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:53:18787
e.exports</t.default@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:53:19564
o@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:53:15848
t.executeRequest/<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:12:90735
v/</</<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:1:60386
r/<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:92:102197
t.executeRequest/<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:52:92770
r@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:62:133500
p/<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:62:130652
Y</<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:12:91554
v/</</<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:1:60386
r/<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:92:102197
t.execute/<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:52:39623
r@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:62:133500
p/<@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:62:130652
t/r.onClick@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:62:44702
r@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:38:59584
a@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:38:55670
s@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:38:55887
h@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:12:49327
m@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:12:49455
r@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:52:186344
processEventQueue@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:12:50517
r@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:91:95984
handleTopLevel@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:91:96057
o@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:91:96508
perform@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:12:72177
batchedUpdates@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:91:94764
o@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:12:12315
dispatchEvent@http://localhost:8080/api/api-docs/swagger-ui-bundle.js:91:97363
from swagger-ui-express.
What version of swagger spec are you using?
Can you post your swagger-ui-express options?
const options = {
swaggerOptions: {
authAction :{ JWT: {name: "JWT", schema: {type: "apiKey", in: "header", name: "Authorization", description: ""}, value: "Bearer <JWT>"} }
}
};
The name of the key in the object and name property need to match the security definition, so for the example you posted your swagger options would need to be:
const options = {
swaggerOptions: {
authAction :{ authentication: {name: "authentication", schema: {type: "apiKey", in: "header", name: "Authorization", description: ""}, value: "Bearer <JWT>"} }
}
};
from swagger-ui-express.
I am using swagger spec 3.0
My swagger-ui-express options are:
var customSwaggerOptions = {
explorer: true,
swaggerOptions: {
authAction: {
JWT: {
name: 'JWT',
schema: {
type: 'apiKey',
in: 'header',
name: 'Authorization',
description: ''
},
value: 'Bearer <my own JWT token>'
}
}
}
}
The 'options' work, because the search bar is visible using the 'explorer : true' property. However, after making sure the name are the same, the errors are the same (in developer console): no request is being made. If I use the 'Authorize' button to log out, I can see the request being made (without authorization header) and I get 401.
The security definition in swagger.json
"securitySchemes": {
"JWT": {
"type": "apiKey",
"name": "Authorization",
"in": "header"
}
}
Edit: pasted wrong code
from swagger-ui-express.
I was able to get this working by having my client put the token in the path as a parameter. This seems to load fine in an iframe using the token for authentication
self.app.use('/api-docs/:token', function (req, res, next) {
req.headers['x-api-token'] = req.params.token;
securityHandlers.ApiHeaderTokenSecurity(req, ["Admin"]).then(function (succeeded) {
if (succeeded) {
next();
} else {
res.status(401).send("Authentication failed");
}
}).catch(function (err) {
self.logger.info(err);
res.status(401).send("Authentication failed");
});
}, swaggerui.serve, swaggerui.setup(self.openapi.apiDoc));
from swagger-ui-express.
Hi, I don't think this feature works right now. I specify JWT validation as follows:
swagger.json
"components": {
"securitySchemes": {
"JWT": {
"description": "",
"type": "apiKey",
"name": "Authorization",
"in": "header"
}
}
},
"security": {
"bearerAuth": []
},
My swagger options
explorer: true,
swaggerOptions: {
authAction: {
JWT: {
name: 'JWT',
schema: {
type: 'apiKey',
in: 'header',
name: 'Authorization',
description: ''
},
value: 'Bearer <my own JWT token>'
}
}
}
An authorization button appears in swagger after adding this code. If it remains untouched, a request is being made as expected. If anything is being filled in to authorization (in a field that pops up after pressing the auth button in top right corner), requests are not being made at all.
Am I doing something wrong?
from swagger-ui-express.
Would a workaround of adding some css to hide the authorization button work in your case? If the request works without touching it?
from swagger-ui-express.
I mean, I want to send authorization header, but if I try as much as adding anything as my token through that button, the request never stops sending.
from swagger-ui-express.
Thank you! I also had an issue with my requestBody.
from swagger-ui-express.
Here's some working code to save your authorization token automatically after you login and to restore it after you refresh the page.
NOTE: Tested only with OpenAPI v3 API schema.
function useSwaggerUI() {
// Serve the Swagger UI.
// See:
// - https://www.npmjs.com/package/swagger-ui-express#custom-swagger-options
// - https://github.com/swagger-api/swagger-ui/blob/master/docs/usage/configuration.md#display
app.use(
API_DOCS_PATH,
swaggerUI.serve,
swaggerUI.setup(apiSpec, {
swaggerOptions: {
docExpansion: "none",
plugins: [useSwaggerUIAuthStoragePlugin()],
},
}),
);
}
function useSwaggerUIAuthStoragePlugin() {
/* eslint-disable */
// prettier-ignore
const afterLoad = function(ui) {
// NOTE: Code inside this afterLoad function will run in the browser!
//
// **Therefore, you cannot use an closure variables in here!**
// Also you should follow ES5 coding style.
//
// See: https://github.com/scottie1984/swagger-ui-express/blob/master/index.js#L239
//
// Other Notes:
// See https://github.com/scottie1984/swagger-ui-express/issues/44
// See https://github.com/swagger-api/swagger-ui/blob/master/src/core/system.js#L344
// See https://github.com/swagger-api/swagger-ui/issues/2915#issuecomment-297405865
var AUTH_SCHEME = "AuthJWT";
// var swaggerOptions = this;
var currentAuthToken = undefined;
setTimeout(function() {
// Restore auth token from localStorage, if any.
var token = localStorage.getItem(AUTH_SCHEME);
if (token) {
setAuthToken(token);
console.log("Restored " + AUTH_SCHEME + " token from localStorage.");
}
// Start polling ui.getState() to see if the user changed tokens.
setTimeout(checkForNewLogin, 3000);
}, 1000);
function checkForNewLogin() {
var stateToken = getAuthTokenFromState();
if (stateToken !== currentAuthToken) {
console.log("Saved " + AUTH_SCHEME + " token to localStorage.");
if (stateToken) {
localStorage.setItem(AUTH_SCHEME, stateToken);
} else {
localStorage.removeItem(AUTH_SCHEME);
}
currentAuthToken = stateToken;
}
// Continue checking every second...
setTimeout(checkForNewLogin, 1000);
}
function getAuthTokenFromState() {
var state = ui.getState();
// Get token from state "auth.authorized[AUTH_SCHEME].value"
return getUIStateEntry(
getUIStateEntry(
getUIStateEntry(getUIStateEntry(state, "auth"), "authorized"),
AUTH_SCHEME
),
"value"
);
}
function getUIStateEntry(state, name) {
if (state && state._root && Array.isArray(state._root.entries)) {
var entry = state._root.entries.find(e => e && e[0] === name);
return entry ? entry[1] : undefined;
}
return undefined;
}
function setAuthToken(token) {
var authorization = {};
authorization[AUTH_SCHEME] = {
name: AUTH_SCHEME,
schema: {
type: "apiKey",
in: "header",
name: "Authorization",
description: "",
},
value: token,
};
var result = ui.authActions.authorize(authorization);
currentAuthToken = token;
return result;
}
};
/* eslint-enable */
return {
afterLoad,
};
}
from swagger-ui-express.
seems issue still persist.
const swaggerOptions = {
swaggerDefinition: {
info: {
version: "1.0.0",
title: "REST API",
description: "REST API Information",
contact: {
name: "AUTH TEST"
},
servers: ["http://localhost:99097"]
},
components: {
securitySchemes: {
bearerAuth: {
description: "JWT Authorization",
type: "https",
scheme: "bearer",
in: "header",
bearerFormat: "JWT",
}
}
},
security: {
bearerAuth: [],
},
},
apis: ["routes/user.routes.js"]
};
I've above configs but i can see only blank page when i click auth button.
from swagger-ui-express.
@emretufekci did you get any solution?
from swagger-ui-express.
@rajuAhmed1705 No, i didn't.
from swagger-ui-express.
Code to save your bearer token dynamically after you login.
const swaggerUi = require("swagger-ui-express");
const YAML = require("yamljs");
const swaggerDocument = YAML.load(
"./SwaggerFileName.yaml"
);
// call this function after user login by passing token
export function setSwaggerTokenHeader(token) {
const swaggerUiOptions = {
swaggerOptions: {
authAction: {
bearerAuth: {
name: "JWT",
schema: {
type: "http",
in: "header",
name: "Authorization",
},
value: `${token}`,
},
},
},
persistAuthorization: true,
};
swaggerUi.setup(swaggerDocument, swaggerUiOptions);
}
YAML config
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat: JWT # optional, for documentation purposes only
paths:
/user/cookies:
get:
tags:
- User Module
summary: get cookies
parameters:
- name: accept
in: header
schema:
type: string
example: application/json, text/plain, */*
- name: content-type
in: header
schema:
type: string
example: application/json
security:
- bearerAuth: [ ]
Security field in paths is required.
from swagger-ui-express.
@jeremyfry thank you for showing how to persist the bearer token!
from swagger-ui-express.
Related Issues (20)
- Apply bearer auth to global scope is not working. HOT 3
- Cannot load two different API specs HOT 6
- Changelog please HOT 2
- I don't understand where swagger.json gets generated... HOT 3
- Getting string instead of array when using multipart form data HOT 2
- feature: ability to serve the docs as a single-file HOT 1
- totally does not load on production HOT 3
- oneOf, anyOf, allOf, not
- refused to execute in browser HOT 3
- Array of strings sent through formdata are converted to array with single string when recieved on nodejs server
- My project is having problems because of assert HOT 3
- "Could not render OperationContainer, see the console."
- Not rendering with $refs HOT 2
- No operations defined in spec!
- Support for OpenAPI Specification 3.1.0 HOT 1
- Using swagger-ui for custom UI rather than swagger-ui-dist?
- [BUG] Changing host on the fly before load is not working
- Vulnerabilities in express
- Route params not filling successfully in nested api controller files using "mergeParams: true"
- [@types/swagger-ui-express] About the impossibility of adding custom js
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from swagger-ui-express.