Add default Bearer token in Swagger Editor - swagger

I want to specify the default value of a Bearer token for authentication in the Swagger Editor. Is it possible?
securitySchemes:
Bearer:
type: apiKey
name: Authorization
in: header
description: Enter your bearer token in the format **Bearer <token>**
security:
- Bearer: []

Related

openapi, springdoc with Swagger Annotations splitting free form application/x-www-form-urlencoded request body into individual characters

I'm trying to migrate from Springfox to springdoc for our Swagger page, and there is one endpoint that I am having a hard time getting working with springdoc. It is mimicking a OAuth2 token endpoint, taking in an application/x-www-form-urlencoded request body with different grant types allowed. I have the generated openapi documentation below. According to the Swagger page, the free form data should be allowed when using schema of type object. However, when I pass in the example values that worked on Springfox and swagger 2 (grant_type=authorization_code&code=xxxxxxxxxx&client_id=xxxxxxxxxx), the request is built out like this (note the body):
curl -X 'POST' \
'http://localhost:8080/v1/token' \
-H 'accept: application/json' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d '0=g&1=r&2=a&3=n&4=t&5=_&6=t&7=y&8=p&9=e&10=%3D&11=a&12=u&13=t&14=h&15=o&16=r&17=i&18=z&19=a&20=t&21=i&22=o&23=n&24=_&25=c&26=o&27=d&28=e&29=%26&30=c&31=o&32=d&33=e&34=%3D&35=x&36=x&37=x&38=x&39=x&40=x&41=x&42=x&43=x&44=x&45=%26&46=c&47=l&48=i&49=e&50=n&51=t&52=_&53=i&54=d&55=%3D&56=x&57=x&58=x&59=x&60=x&61=x&62=x&63=x&64=x&65=x'
Is there something that I am doing wrong in the openapi yaml, or am I putting the request body in incorrectly on the swagger page?
Swagger documentation:
OpenAPI YAML to be used at https://editor.swagger.io/
openapi: 3.0.1
info:
title: Test API
description: Testing
version: "1.0"
servers:
- url: http://localhost:8080
description: Generated server url
security:
- api: []
paths:
/v1/token:
post:
tags:
- token-controller
description: Oauth 2 Access Token.
operationId: getOauthAccessToken
requestBody:
content:
application/x-www-form-urlencoded:
schema:
type: object
examples:
authorization_code grant type:
description: authorization_code grant type
value: grant_type=authorization_code&code=xxxxxxxxxx&client_id=xxxxxxxxxx
client_credentials grant type:
description: client_credentials grant type
value: grant_type=client_credentials&client_id=xxxxxxxxxx&client_secret=xxxxxxxxxx
refresh_token grant type:
description: refresh_token grant type
value: grant_type=refresh_token&refresh_token=xxxxxxxxxx
responses:
'200':
description: OK
content:
application/json:
schema:
$ref: '#/components/schemas/OauthAccessTokenResponseView_V1'
components:
schemas:
OauthAccessTokenResponseView_V1:
type: object
properties:
scope:
type: string
access_token:
type: string
refresh_token:
type: string
token_type:
type: string
expires_in:
type: integer
format: int64
description: 'The Oauth 2 Access Token response: https://www.oauth.com/oauth2-servers/access-tokens/access-token-response/'
securitySchemes:
api:
type: http
scheme: bearer
Your definition looks fine. This is a bug (or limitation?) in Swagger UI related to OpenAPI 3 examples keyword and form data. Please report it in the issue tracker: https://github.com/swagger-api/swagger-ui/issues
I could not find a working way to provide multiple examples for form data.
From the documentation point of view, I would recommend updating the request body schema to define the exact expected properties. Below is one possible variant that uses oneOf and property-level example values. But unfortunately there are other known issues with the rendering and "try it out" for form data with oneOf.
requestBody:
content:
application/x-www-form-urlencoded:
schema:
oneOf:
- $ref: '#/components/schemas/AuthorizationCodeTokenRequest'
- $ref: '#/components/schemas/ClientCredentialsTokenRequest'
- $ref: '#/components/schemas/RefreshTokenRequest'
...
components:
schemas:
AuthorizationCodeTokenRequest:
type: object
required:
- grant_type
- code
- client_id
properties:
grant_type:
type: string
enum: [authorization_code]
code:
type: string
example: xxxxxxxxxx
client_id:
type: string
example: xxxxxxxxxx
ClientCredentialsTokenRequest:
type: object
required:
- grant_type
- client_id
- client_secret
properties:
grant_type:
type: string
enum: [client_credentials]
client_id:
type: string
example: xxxxxxxxxx
client_secret:
type: string
format: password
example: xxxxxxxxxx
RefreshTokenRequest:
type: object
required:
- grant_type
- refresh_token
properties:
grant_type:
type: string
enum: [refresh_token]
refresh_token:
type: string
format: password
example: xxxxxxxxxx
Do you actually need to document the payload for the token endpoint? If it's a standard OAuth 2.0 token endpoint as per RFC 6749, you could define it in securitySchemes instead:
paths:
/something:
get:
description: One of the endpoints that require OAuth Bearer token.
security:
- oauth2: [] # <-----
responses:
...
components:
securitySchemes:
oauth2: # <-----
type: oauth2
flows:
authorizationCode:
authorizationUrl: '???' # TODO
tokenUrl: /v1/token
refreshUrl: '???' # TODO
scopes: {}
clientCredentials:
tokenUrl: /v1/token
refreshUrl: '???' # TODO
scopes: {}

role based token authentication with apikey security in openapi swagger connexion

Describing the problem
I was struggeling the last few days to figure out how to use apikey security in openapi, swagger, connexion for role based token authentication. The following OpenAPI 3.0 endpoint definition:
/lab/samples/list:
get:
tags:
- lab
summary: get a list of all registered samples
operationId: list_samples
responses:
"200":
description: successfully returned all available samples and their notification status
content:
application/json:
schema:
type: array
items:
$ref: '#/components/schemas/Sample-For-Lab'
x-content-type: application/json
"400":
description: invalid request
content:
application/json:
schema:
$ref: '#/components/schemas/inline_response'
security:
- bearerAuth: ['labuser']
with the corresponding security definition
securitySchemes:
bearerAuth:
type: apiKey
name: Authorization
in: header
x-apikeyInfoFunc: swagger_server.controllers.authorization_controller.check_bearerAuth
So far so good. I built the corresponding server stubs using swagger-codegen, which follow the connexion security model and provide two fields api_key i.e. the bearer token and 'required_scopes' i.e. which should contain 'labuser'. When accessing the endpoint, the controller function is called:
def check_adminuserAuth(api_key, required_scopes):
return {'sample_key' : 'sample_value}
While the bearer token is properly passed, required_scopes is None. So there's no way of actually validating if credentials and permissions shown in the provided token actually match the endpoint's required scope of labuser in the authorization controller. I thought about handling validation in the called endpoints list_systemusers() but the token is no passed on by connexion.
Not supported in OpenAPI 3.0
After doing some digging, I found out that OpenAPI 3.0 provides apiKey validation on a global API level (i.e. authenticated or not), but does not offer support for individual scopes per endpoint. If you want individual scopes, you need to switch to OAuth security. However support for security scopes through apiKey security is coming in OpenAPI 3.1
Workaround
So for now the only way of making bearer token security with individual scopes work, is to actually define a security scheme for every scope e.g.
securitySchemes:
adminuserAuth:
type: apiKey
description: Provide your bearer token in the format **Bearer <token>**
name: Authorization
in: header
x-apikeyInfoFunc: swagger_server.controllers.authorization_controller.check_adminuserAuth
statsuserAuth:
type: apiKey
description: Provide your bearer token in the format **Bearer <token>**
name: Authorization
in: header
x-apikeyInfoFunc: swagger_server.controllers.authorization_controller.check_statsuserAuth
labuserAuth:
type: apiKey
description: Provide your bearer token in the format **Bearer <token>**
name: Authorization
in: header
x-apikeyInfoFunc: swagger_server.controllers.authorization_controller.check_labuserAuth
and on the path definition then add your required security authentication schemes
security:
- labuserAuth: []
- adminuserAuth: []
x-openapi-router-controller: swagger_server.controllers.lab_controller
Now I know by which authorization controller method is called the required scope a user needs to show and therefore can validate it against the ones shown in the token.

Flask RESTPlus swagger interface doesn't pass Authorisation header on to curl request

Running latest (and now old due to the switchover to flask REST-X) flask RESTPlus using the authorization functionality for the swagger interface with a Bearer token as follows:
authorizations = {
'apikey': {
'type': 'apiKey',
'in': 'header',
'name': 'Bearer '
}
But although the "Authorise" box comes up in the swagger interface, and I can put a token in there, it doesn't get added to the requests coming out or the curl format that swagger provides, so we can see clearly it's not being picked up. What's going on here and how do I fix it?
Make sure the code also has annotations that would add security to individual operations or globally. This is needed to actually attach the Authorization header to operations.
In other words, the generated OpenAPI definition should contain the following.
If using OpenAPI 2.0:
swagger: '2.0'
securityDefinitions:
apikey:
type: apiKey
in: header
name: Authorization
security:
- apiKey: []
If using OpenAPI 3.0:
openapi: 3.0.0
components:
securitySchemes:
apikey:
type: apiKey
in: header
name: Authorization
# or using OAS3 Bearer auth scheme
# apiKey:
# type: http
# scheme: bearer
security:
- apiKey: []

auth0, getting Schema error at securityDefinitions.auth0

i get this error on swagger editor when using the auth0
Schema error at securityDefinitions.auth0
is not exactly one from <#/definitions/basicAuthenticationSecurity>,<#/definitions/apiKeySecurity>,<#/definitions/oauth2ImplicitSecurity>,<#/definitions/oauth2PasswordSecurity>,<#/definitions/oauth2ApplicationSecurity>,<#/definitions/oauth2AccessCodeSecurity>
Jump to line 67
where my .yaml file is like:
securityDefinitions:
auth0:
type: oauth2
authorizationUrl: https://domain.auth0.com/authorize
flow: implicit
tokenName: id_token
scopes:
openid: Grant access to user
apiKey:
type: apiKey
name: api-key
in: query
apiKey1:
type: apiKey
name: api-key
in: header
what am i missing?
Remove tokenName - it's not a supported field.
Check the specification to see which fields are allowed in securityDefinitions:
https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#securitySchemeObject

Swagger same path specified twice

Is it possible to have same path appear more than once in one API spec which is being rendered by Swagger-UI?
Should I create separate api specs and load two instances of Swagger-UI? What is the best way to handle this?
For ex. I have endpoint called /oauth/token which I want to document with one set of parameters for OAuth Authorization Code flow and the same endpoint /oauth/token documents for client_credentials flow with different set of parameters.
/oauth/token:
post:
summary: token endpoint for authorization_code flow
parameters:
- name: code
type: string
description: Required for Authorization Code Flow
in: formData
required: true
- name: grant_type
type: string
description: Grant Type should be specified as authorization_code
in: formData
required: true
default: authorization_code
enum:
- authorization_code
- client_credentials
- name: client_id
type: string
description: Consumer Key
in: formData
required: true
- name: client_secret
type: string
description: Consumer Secret
in: formData
required: true
- name: endOtherSessions
in: formData
type: boolean
required: false
default: false
description: Optional parameter. Default is false - do not allow concurrent login. Send true to end any other user sessions.
tags:
- OAuth2 Authorization Code
Same endpoint for client_credentials flow
/oauth/token2:
post:
summary: token for client credentials
parameters:
- name: grant_type
type: string
description: Grant Type should be specified as client_credentials
in: formData
required: true
default: client_credentials
enum:
- authorization_code
- client_credentials
- name: client_id
type: string
description: Consumer Key
in: formData
required: true
- name: client_secret
type: string
description: Consumer Secret
in: formData
required: true
tags:
- OAuth2 Client Credentials
Since the question is about OAuth2 rather than a single endpoint with different parameters, then the solution is actually different.
Swagger has a specific way to document authorization methods, including the 4 common OAuth2 flows.
These are described using the Security Definitions Object which is located at the top Swagger object.
Within it, you can define one or more OAuth2 flows. The spec itself provides a sample for the implicit flow, but others follow a similar structure. The difference is by which fields are provided, namely authorizationUrl and tokenUrl (depending on the flow type).
Once you have that, you can specify which security schemes are required. You can specify it for all the operations at the Swagger object or at the Operation level.
The spec allows you to define that a set of security methods are required together, or that the user can choose between given sets.

Resources