swagger-api / swagger-ui

Swagger UI is a collection of HTML, JavaScript, and CSS assets that dynamically generate beautiful documentation from a Swagger-compliant API.
https://swagger.io
Apache License 2.0
26.31k stars 8.91k forks source link

Automatic token refresh for REST API with OpenID Connect authentication? #7257

Open retrofreak83 opened 3 years ago

retrofreak83 commented 3 years ago

Q&A (please complete the following information)

Content & configuration

I am developing an application having a REST API that is secured by Spring Security, using Keycloak to provide OpenID Connect functionalities. The OpenAPI specification is generated using Springdoc. AFAIK, the correct way of getting SwaggerUI to authenticate against OpenID Connect is to use OpenID Connect Discovery.

Swagger/OpenAPI definition:

openapi: 3.0.1
info:
  title: NEW API
  description: This document specifies the API of NEW
  version: v0.1-SNAPSHOT
servers:
  - url: 'http://localhost:8080'
    description: Generated server url
security:
  - oidc: []
paths:
  /p/list:
    get:
      tags:
        - plugin-controller
      operationId: getAllOperations
      responses:
        '200':
          description: OK
          content:
            '*/*':
              schema:
                type: array
                items:
                  type: string
        '400':
          description: Bad Request
          content:
            '*/*':
              schema:
                $ref: '#/components/schemas/JSONResponse'
        '401':
          description: Unauthorized
          content:
            '*/*':
              schema:
                $ref: '#/components/schemas/JSONResponse'
        '403':
          description: Forbidden
          content:
            '*/*':
              schema:
                $ref: '#/components/schemas/JSONResponse'
        '500':
          description: Internal Server Error
          content:
            '*/*':
              schema:
                $ref: '#/components/schemas/JSONResponse'

components:
  schemas:
    JSONResponse:
      type: object
      properties:
        errorData:
          type: string
          description: the raw error data
        token:
          type: string
  securitySchemes:
    oidc:
      type: openIdConnect
      openIdConnectUrl: 'http://localhost:8888/auth/realms/new/.well-known/openid-configuration'

How can we help?

Authorization works well in principal, but the application needs to do a token refresh automatically and regularly. Currently, I can send valid request to the API until the validity of the token acquired during login has expired. In the SwaggerUI documentation, I did not find how to configure such a thing like token refresh. Is SwaggerUI able to perform an automatic token refresh or is there eventually a possibility that the user can trigger it manually?

Eli-Black-Work commented 3 years ago

We're looking for this as well.

major-mayer commented 3 years ago

Same problem here using Swagger UI with FastAPI. I can specify a refresh_url in the oauth2_schema, but this doesn't work as expected:

oauth2_scheme = OAuth2AuthorizationCodeBearer(
    authorizationUrl=ConfigHandler.get_config()["oauth2"]["authorization_server"]["authorization_url"],  # The endpoint to get the authorization token
    tokenUrl=ConfigHandler.get_config()["oauth2"]["authorization_server"]["token_url"],    # The endpoint to get the actual access token
    refreshUrl=ConfigHandler.get_config()["oauth2"]["authorization_server"]["token_url"]
)
Eli-Black-Work commented 3 years ago

We tried specifying refreshUrl, too, but weren't able to get it to work.

labedzkim commented 3 years ago

Having this would help much in testing our APIs.

tim-lai commented 3 years ago

afaik, Swagger UI does not currently have token refresh. Happy to accept contributions, especially in this subject of authorization/authentication. 😉

tim-lai commented 3 years ago

Thinking about this more, one might be able to use requestIntercepters to define custom handling to an auth request.

alexted commented 2 years ago

Any progress on this problem? I also need this functionality.

rakum23 commented 2 years ago

Any progress on this? it will be great help for developers

xianrui69 commented 1 year ago

function authorize() { if ($('.btn.authorize').length < 1) return; if (!web.getCookie('accessToken')) return; let a = { CoreAPI: { name: 'CoreAPI', schema: swg_ui.authSelectors.definitionsToAuthorize().get(0).get('CoreAPI'), value: 'Bearer ' + web.getCookie('accessToken') } } swg_ui.authActions.authorize(a) }

rozzilla commented 1 year ago

Any progress on this? it will be great help for developers

+1

amanuel-girma commented 1 year ago

I am also looking for this feature in swagger, is there any progress?

ogurevich commented 1 year ago

+1

AswiniKumarV commented 10 months ago

Is there any update on this feature? Do you know anything @tim-lai

hjrb commented 9 months ago

I'm suffering with you

sajankp commented 8 months ago

Wished the fastapi docs could do this

tarun3301 commented 3 months ago

any progress in this?

tom300z commented 2 months ago

For anyone looking for a quick workaround i've written this js which automatically patches OAuth token refreshing into SwaggerUI at runtime: https://gist.github.com/tom300z/ee48163e5c58e8572a251a593f2026e7

hjrb commented 2 months ago

For anyone looking for a quick workaround i've written this js which automatically patches OAuth token refreshing into SwaggerUI at runtime: https://gist.github.com/tom300z/ee48163e5c58e8572a251a593f2026e7

If you are getting "Cannot patch OAuth token refresh hook. Missing patch target function "window.ui.authActions.authorizeOauth2". This is how I include the custom-swagger.js in a ASP.NET Core 8 app in the programs.cs of the web application server

    app.UseSwaggerUI(c => {
        // ...
        c.InjectJavascript("/custom-swagger.js");
//...
    });

Still getting the error

SthPhoenix commented 1 month ago

For anyone looking for a quick workaround i've written this js which automatically patches OAuth token refreshing into SwaggerUI at runtime: https://gist.github.com/tom300z/ee48163e5c58e8572a251a593f2026e7

Any hints on how to actually inject this js into swagger? Using i.e. FastAPI?