BartusZak
BartusZak

Reputation: 1243

Swagger with Google OAuth 2.0 authorization

Swagger passes access_code by default to headers. Is it possible to pass id_token?

I'm documenting my NodeJS REST API with swagger.yaml version 2.0

enter image description here

Upvotes: 2

Views: 7904

Answers (2)

Renan Siqueira
Renan Siqueira

Reputation: 11

You can make Swagger or Nswagg use a different token (id_token or access_token) by setting the x-tokenName in the security configuration, such as following:

services.AddSwaggerDocument(config =>
{
    config.PostProcess = document =>
    {
        document.Info.Title = "API OpenBankWeb";
        document.Info.Description = "Uma simples Web API feita em ASP.NET Core consumindo AWS.\nClique nos títulos abaixo para expandir.";
    };
    config.AddSecurity("oauth2", new NSwag.OpenApiSecurityScheme
    {
        Type = OpenApiSecuritySchemeType.OAuth2,
        ExtensionData = new Dictionary<string, object>
        {
            { "x-tokenName", "id_token" }
        },
        Flows = new OpenApiOAuthFlows
        {
            AuthorizationCode = new OpenApiOAuthFlow
            {
                AuthorizationUrl = _domain + "/oauth2/authorize",
                TokenUrl = _domain + "/oauth2/token"
            }
        }
    });

This can be very handy when using AWS Cognito, since it uses only id token for authentification.

Upvotes: 1

Helen
Helen

Reputation: 97560

Yes this is possible even though it's not a good idea as mentioned by @DalmTo.

You need to add x-tokenName: id_token to the Google OAuth security definition in your API definition.

swagger: '2.0'
...

securityDefinitions:
  google_oauth:
    type: oauth2
    description: Google OAuth
    flow: accessCode
    authorizationUrl: https://accounts.google.com/o/oauth2/v2/auth
    tokenUrl: https://www.googleapis.com/oauth2/v4/token
    x-tokenName: id_token   # <-------
    scopes:
      ...

Note: To use x-tokenName in OpenAPI 2.0 definitions you need Swagger UI 3.8.12+; to use it in OpenAPI 3.0 you need Swagger UI 3.25.0+.

Upvotes: 3

Related Questions