首页 文章

Swagger UI - Oauth密码流,检索并添加令牌到授权请求

提问于
浏览
0

我刚开始在MVC中使用Swagger UI for ASP.Net API web项目 . 我认识的大多数部分都是正确的,除了身份验证 .

我正在使用OAuth ASP.Net Identity . 以下是我的设置:

SwaggerConfig.cs

c.OAuth2("oauth2")
                        .Description("OAuth2 Implicit Grant")
                        .Flow("password")
                        .AuthorizationUrl("/api/Account/ExternalLogin")
                        .TokenUrl("/Token")
                        .Scopes(scopes =>
                        {
                            scopes.Add("values:read", "Read access to protected resources");
                            scopes.Add("values:write", "Write access to protected resources");
                        });

         c.OperationFilter<AssignOAuth2SecurityRequirements>();

AssignOAuth2SecurityRequirements.cs

internal class AssignOAuth2SecurityRequirements : IOperationFilter
    {
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            var authorizeAttributes = apiDescription.ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>();

            if (!authorizeAttributes.Any())
                return;

            if (operation.security == null)
                operation.security = new List<IDictionary<string, IEnumerable<string>>>();

            var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
            {
                { "oauth2", Enumerable.Empty<string>() }
            };

            operation.security.Add(oAuthRequirements);

        }
    }

index.html

<script>
window.onload = function() {

  // Build a system
  const ui = SwaggerUIBundle({
      url: "http://localhost:17527/swagger/docs/v1",
    dom_id: '#swagger-ui',
    deepLinking: true,
    presets: [
      SwaggerUIBundle.presets.apis,
      SwaggerUIStandalonePreset
    ],
    plugins: [
      SwaggerUIBundle.plugins.DownloadUrl
    ],
    layout: "StandaloneLayout"
  })

  window.ui = ui
}
</script>

在从APP页面授权/令牌请求时 .

但是当我尝试访问值 endpoints 时,它会抛出错误 .

原因是请求缺少应该在 Headers 中的Bearer Token

我已经尝试了一些解决方案,但无法解决它 .

提前致谢 .

1 回答

  • 1

    我最近也尝试了这个,你必须在方法级别而不是在控制器级别放置[Authorize]属性然后它将工作并在每个请求中发送Bearer令牌 .

相关问题