浏览器刷新 Laravel 时丢失 SwaggerUI JWT 令牌

时间:2021-04-01 08:22:40

标签: php laravel swagger swagger-ui openapi

我使用 DarkaOnLine/L5-Swagger 来记录我的 API。 我使用承载 JWT 进行身份验证。当我创建一个新端点或对现有端点进行更改时,我需要刷新 SwaggerUI 页面。然后我必须重新输入令牌。我该如何解决这个问题?

我在 this issue 上尝试过的解决方案对我也不起作用。

这对我不起作用。

(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);
})();

1 个答案:

答案 0 :(得分:2)

找到了解决方案。只需将 "persistAuthorization: true" 放入 SwaggerUIBundle json 就解决了我的问题。

供应商\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,
})

您可以找到其他需要的参数 here