Search code examples
phplaravelswaggerswagger-uiopenapi

Losing SwaggerUI JWT Token when browser refreshed Laravel


I use DarkaOnLine/L5-Swagger to documentate my api. I use Bearer JWT for authentication. When i create a new endpoint or make changes on existing one i need to refresh SwaggerUI page. Then i have to re-enter the token. How can i solve this?

I ve tried solutions on this issue didn't work for me also.

This didn't work for me.

(function () {
const API_KEY = 'ApiKey';
setTimeout(function () {

  // store the api key in the local storage
  var originalAuthorize = ui.authActions.authorize;
  
  ui.authActions.authorize = function (payload) {
    window.localStorage.setItem(API_KEY, payload.ApiKeyScheme.value);
    return originalAuthorize(payload);
  };

  // if logout is clicked delete the api key in the local storage
  var originalLogout = ui.authActions.logout;

  ui.authActions.logout = function (payload) {
    window.localStorage.removeItem(API_KEY);
    return originalLogout(payload);
  };

  // If token already exists, load it from local storage
  const apiKey = window.localStorage.getItem(API_KEY);
  if (apiKey) {
    window.ui.preauthorizeApiKey('ApiKeyScheme', apiKey);
  }
}, 1000);
})();

Solution

  • Found the solution. Just putting "persistAuthorization: true" to SwaggerUIBundle json solved my problem.

    vendor\l5-swagger\index.blade.php

    const ui = SwaggerUIBundle({
    dom_id: '#swagger-ui',
    
    url: "{!! $urlToDocs !!}",
    operationsSorter: {!! isset($operationsSorter) ? '"' . $operationsSorter . '"' : 'null' !!},
    configUrl: {!! isset($configUrl) ? '"' . $configUrl . '"' : 'null' !!},
    validatorUrl: {!! isset($validatorUrl) ? '"' . $validatorUrl . '"' : 'null' !!},
    oauth2RedirectUrl: "{{ route('l5-swagger.'.$documentation.'.oauth2_callback') }}",
    
    requestInterceptor: function(request) {
      request.headers['X-CSRF-TOKEN'] = '{{ csrf_token() }}';
      return request;
    },
    
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    
    layout: "StandaloneLayout",
    
    persistAuthorization: true,
    })
    

    You can find other needed parameters here.