I am learning to use Swagger to document my API, and everything was well-explained until I got to the authentication portion. To give you some context of my API's authentication: it uses passport-jwt to authenticate users, sends an access token in the response body, and sets a refresh token in an httpOnly cookie. This is the swagger.json documentation I have so far:
{
"swagger": "2.0",
"info": {
"title": "API",
"description": "Coin-based API",
"version": "1.0.0"
},
"host": "localhost:4000",
"schemes": ["http"],
"consumes": ["application/json"],
"produces": ["application/json"],
"components": {
"securitySchemes": {
"bearerAuth": {
"type": "http",
"scheme": "bearer",
"in": "header",
"bearerFormat": "JWT"
}
}
},
"paths": {
"/api/users/transfer": {
"patch": {
"summary": "Transfer coins from one user to another",
"description": "Transfers coins from one user to another",
"security": [
{
"bearerAuth": []
}
],
"parameters": [
{
"name": "body",
"in": "body",
"schema": {
"type": "object",
"properties": {
"amount": {
"example": "any"
},
"recipient": {
"example": "any"
}
}
}
}
],
"responses": {
"200": {
"description": "Returns the user's new balance"
},
"400": {
"description": "Cannot transfer to yourself and/or Amount must be greater than 0"
},
"401": {
"description": "Unauthorized"
},
"403": {
"description": "Insufficient funds"
},
"404": {
"description": "User not found"
}
}
}
},
I couldn't find a good reference on what the best practices are to let the client know that he needs to send a access token in the header. Right now on my swagger Ui, I see a an open lock and no information about the authorization process. What should I do?
I expect the client to see the information about the authorization process and able to send a request with an access token.
Related
I am creating an C# ASP.NET Core 2.0 REST API, all going well for the most part. It is using MVC routing to gen the REST API. The controllers are pretty simple.
// POST: api/Volume/{zoneID}/Set/{volume}
[HttpPost("{zoneId:int}/[action]/{volume:int}", Name = "Set")]
public IActionResult Set(int zoneId, int volume)
{
return CreateAndSend(strZonesLevel, zoneId, $"{volume:X2}");
}
Using the latest of everything, installed Swagger/Swashbuckle for AspNetCore 2.3.0 and the UI comes up with the APIs and all. The SwashBuckle UI works well, I can test the API etc.
The one exception is that on the UI, the Response type ALWAYS comes back as "Unknown Response Type."
https://i.stack.imgur.com/6qqBh.jpg
I have the following attributes in front of my class (all methods return the same type)
[Produces("application/json")]
[Route("api/Volume")]
[ProducesResponseType(typeof(ControllerResponseModel), 200)]
[ProducesResponseType(typeof(ControllerResponseModel), 400)]
[ProducesResponseType(typeof(ControllerResponseModel), 500)]
The generated JSON seems allright, the ControllerResponseModel is in the definition, and referenced in all the right places by the Volume API. Here is a subset.
{
"swagger": "2.0",
"info": {
"version": "v1",
"title": "AVController API"
},
"paths": {
"/api/Volume/{zoneId}/Set/{volume}": {
"post": {
"tags": ["Volume"],
"operationId": "ApiVolumeByZoneIdSetByVolumePost",
"consumes": [],
"produces": ["application/json"],
"parameters": [
{
"name": "zoneId",
"in": "path",
"required": true,
"type": "integer",
"format": "int32"
},
{
"name": "volume",
"in": "path",
"required": true,
"type": "integer",
"format": "int32"
}
],
"responses": {
"200": {
"description": "Success",
"schema": {
"type": "array",
"items": { "$ref": "#/definitions/ControllerResponseModel" }
}
},
"400": {
"description": "Bad Request",
"schema": {
"type": "array",
"items": { "$ref": "#/definitions/ControllerResponseModel" }
}
},
"500": {
"description": "Server Error",
"schema": {
"type": "array",
"items": { "$ref": "#/definitions/ControllerResponseModel" }
}
}
}
}
}
},
"definitions": {
"ControllerResponseModel": {
"type": "object",
"properties": {
"command": { "type": "string" },
"message": { "type": "string" },
"url": { "type": "string" }
}
}
}
}
Any ideas why the UI would not be showing the return type and value? I have tried numerous things, like using gets instead of posts as well as using the [SwaggerResponse] attributes, but the results are the same.
This has been identified as an Edge browser issue with Swashbuckle, not the code posted here. It is reproducible on many sites. Issue has posted on GitHub # https://github.com/swagger-api/swagger-ui/issues/4337
I am using Swagger-ui version 3.0.2, I have hosted it locally and provided it my Json file and API it opens the document fine and lists all the method in the json file, after i put basic authentication in it, i did changes in the .JSON file, but there are some methods which i want to mark anonymous.
{
"swagger": "2.0",
"info": {
"description": "description",
"version": "1.0",
"title": "API"
},
"host": "localhost",
"schemes": [
"http"
],
"securityDefinitions": {
"anonymous_auth": {
"type": ""
},
"basic_auth": {
"type": "basic",
"name": "basic_auth",
"description": "Basic Authentication"
},
"token": {
"type": "apiKey",
"description": "API Token Authentication",
"name": "apikey",
"in": "header"
}
},
"security": [
{
"basic_auth": [ ]
},
{
"token": [ ]
}
],
"paths": {
//somthing
},
"definitions": {
//something
}
}
By using security atribute in this way it will secure complete file, but i have some methods which should be anonymous.
To remove global security, add an empty security array to the operation:
"paths": {
"/something:": {
"get": {
"security": [],
...
}
}
}
Also, your spec is not valid:
Remove anonymous_auth.
Remove name from basic_auth - name is only used in apiKey security schemes to specify the name of the header or query parameter that will contain the API key.
After deploying AWS API Gateway via CLI (using put-rest-api and create-deployment) I want to do some testing of my API description in Postman.
After exporting the API via AWS Console (MyAPI - Stages - MyStage - Export - Postman) no body content is imported to Postman.
Does anyone know how to solve this?
When you export with postman extensions, the swagger file contains the definition of the model and the fact that its a parameter to POST, but postman does not show it in content. This is how postman import works. There is a feature request for this in gihub https://github.com/postmanlabs/postman-app-support/issues/1235
...
"/": {
"post": {
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"parameters": [
{
"in": "body",
"name": "TestModel",
"required": true,
"schema": {
"$ref": "#/definitions/TestModel"
}
}
],
...
"definitions": {
"TestModel": {
"type": "object",
"properties": {
"photos": {
"type": "object",
"properties": {
"page": {
"type": "integer"
},
"pages": {
"type": "string"
}
...
}
}
},
"title": "TestModel"
}
}
}
I am newer in Swagger tool. I try to test my Restfull application with swagger editor. I used basic authentication to access the web service.
In the Swagger-UI, the preview looks correct, i.e. Content-Type: application/json and the json is in the body.But When I send GET request from the Swagger editor to server, I got an error.
ERROR Server not found or an error occurred
My Swagger
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Swagger Petstore (Simple)",
"description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification",
"termsOfService": "http://helloreverb.com/terms/",
"contact": {
"name": "Swagger API team",
"email": "abc#gmail.com",
"url": "http://avfg.com"
},
"license": {
"name": "MIT",
"url": "http://opensource.org/licenses/MIT"
}
},
"host": "127.0.0.1:8xxx",
"basePath": "/v1",
"schemes": [
"http"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"paths": {
"/facedetect/{username}/{albumname}/{imagename}": {
"get": {
"description": "Returns all pets from the system that the user has access to",
"operationId": "findPets",
"produces": [
"application/json",
"application/xml"
],
"parameters": [
{
"name": "username",
"in": "path",
"description": "tags to filter by",
"required": true,
"type": "string"
},
{
"name": "albumname",
"in": "path",
"description": "maximum number of results to return",
"required": true,
"type": "string"
},
{
"name": "imagename",
"in": "path",
"description": "maximum number of results to return",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "pet response",
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/pet"
}
}
},
"default": {
"description": "unexpected error",
"schema": {
"$ref": "#/definitions/errorModel"
}
}
}
}
}
},
"definitions": {
"pet": {
"type": "object",
"required": [
"id",
"name"
],
"properties": {
"id": {
"type": "integer",
"format": "int64"
},
"name": {
"type": "string"
},
"tag": {
"type": "string"
}
}
},
"errorModel": {
"type": "object",
"required": [
"code",
"message"
],
"properties": {
"code": {
"type": "integer",
"format": "int32"
},
"message": {
"type": "string"
}
}
}
}
}
Please help me.
Thanks in advance.
Make sure that you have your server running.
If you have swagger installed, you can do
swagger project start
I got the solution.
Its CORS issue. My browser was blocking cors requests. I have installed a Chrome extension that adds Access-Control-Allow-Origin to outgoing requests.
I had simillar problem
this is CORS, but :
in nodeJS i have set:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, UPDATE, DELETE, OPTIONS')
res.header("Content-Type", "application/json");
next();
});
but it helps only when request was without authorization (api-key). To make it works I have to change and use:
const cors = require('cors');
app.use(cors());
hope it is helpfull
We are using swagger 2.0 to document our .Net Web API's which we are hosting in Azure behind Azure API Management. I am having troubles getting the documentation to detail the complex objects that are being posted as part of the body. Azure shows no details about the object at all leaving me to have to document them myself. Below is the json file that I imported into Azure API Management.
{
"swagger": "2.0",
"info": {
"version": "1.0.0",
"title": "Hotel Search",
"description": "The seodecnvewjkl"
},
"basePath": "/v1",
"consumes": [
"application/xml",
"application/json"
],
"produces": [
"application/xml",
"application/json"
],
"schemes": [
"http",
"https"
],
"paths": {
"/hotels/search": {
"post": {
"operationId": "searchCommand",
"description": "Searches for hotels",
"parameters": [
{
"name": "hotelSearchRq",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/HotelSearchRq"
}
}
],
"responses": {
"200": {
"description": "Successful response",
"schema": {
"title": "HotelSearchRs",
"$ref": "#/definitions/HotelSearchRs"
}
},
"400": {
"description": "Bad Request"
},
"404": {
"description": "Unauthorised"
}
}
},
"get": {
"operationId": "searchQuery",
"parameters": [
{
"name": "CorrelationId",
"in": "query",
"type": "string"
}
],
"responses": {
"200": {
"description": "Successful response"
}
}
}
}
},
"definitions": {
"StayDetail": {
"type": "object",
"properties": {
"NumberOfGuests": {
"type": "integer"
},
"CheckinDate": {
"type": "string",
"format": "date",
"description": "the date that the stay starts from"
}
}
},
"HotelSearchCriteria": {
"type": "object",
"properties": {
"MaximumResults": {
"type": "integer",
"format": "int64"
},
"StayDetails": {
"$ref": "#/definitions/StayDetail"
}
}
},
"HotelSearchRq": {
"type": "object",
"properties": {
"CustomerTransactionIdentifier": {
"type": "string",
"description": "The customers transaction identifier"
},
"search_criteria": {
"$ref": "#/definitions/HotelSearchCriteria"
}
}
},
"HotelSearchRs": {
"type": "object"
}
}
}
Azure Api Management operation screen
Can someone please help me with how I can get the body documented automatically from the swagger documentation?
Currently the request and response body information from a Swagger doc are not displayed in the developer portal documentation.
This is no longer the case. Samples and schema are displayed in the developer portal.