Authorization for JWT bearer in Swashbuckle .NET Core 2

前端 未结 3 1180
-上瘾入骨i
-上瘾入骨i 2020-12-16 19:06

I use tokens generated by an authentication service for my app. No problems there. Now I have introduced Swashbuckle to document my API an I can authenticate as follows by s

3条回答
  •  伪装坚强ぢ
    2020-12-16 19:26

    If you define in code

    c.AddSecurityDefinition("jwt", new ApiKeyScheme()
    { 
       In = "header", Description = "Please insert JWT with Bearer into field", Name = "Authorization", Type = "apiKey" });
    

    and then use it in not in .Parameters, but in .Security

    operation.Security = new List>> {
                new Dictionary>
                {
                    {"jwt", _scopes }
                }
    

    then everything should work:

    I do the same as you do, but you should add like follows (for oauth2 or jwt bearer token auth):

        public static class ServiceCollectionExtension
    {
        private static string XmlCommentsFilePath
        {
            get
            {
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var fileName = Assembly.GetEntryAssembly().GetName().Name + ".xml";
                return Path.Combine(basePath, fileName);
            }
        }
    
        public static void AddMySwagger(
            this IServiceCollection services,
            ApiVersion defaultApiVersion,
            Func info,
            string authority = null,
            Dictionary scopes = null)
        {
            services.AddMvcCore().AddVersionedApiExplorer(o => o.GroupNameFormat = "'v'VVV");
    
            services.AddApiVersioning(o =>
            {
                o.ReportApiVersions = true;
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = defaultApiVersion;
            });
    
            services.AddSwaggerGen(
                options =>
                {
                    var provider = services.BuildServiceProvider()
                        .GetRequiredService();
    
                    foreach (var description in provider.ApiVersionDescriptions)
                    {
                        if (!description.IsDeprecated)
                            options.SwaggerDoc(description.GroupName, info(description));
                    }
    
                    options.OperationFilter();
    
                    options.IncludeXmlComments(XmlCommentsFilePath);
    
                    if (!string.IsNullOrEmpty(authority))
                    {
                        options.AddSecurityDefinition("jwt", new ApiKeyScheme()
                        {
                            Description = "JWT Authorization header using the Bearer scheme. Example: \"Bearer {token}\"",
                            Name = "Authorization",
                            In = "header",
                            Type = "apiKey"
                        });
                        //options.AddSecurityDefinition("oauth2", new OAuth2Scheme
                        //{
                        //  Flow = "implicit",
                        //  AuthorizationUrl = $"{authority}/connect/authorize",
                        //  Scopes = scopes ?? new Dictionary()
                        //});
                        options.OperationFilter(scopes?.Select(_ => _.Key).ToList() ?? new List());
                    }
                });
        }
    
        class AuthorizeCheckOperationFilter : IOperationFilter
        {
            private readonly IEnumerable _scopes;
    
            public AuthorizeCheckOperationFilter(IEnumerable scopes)
            {
                _scopes = scopes;
            }
    
            public void Apply(Operation operation, OperationFilterContext context)
            {
                var hasAuthorize = context.ApiDescription.ControllerAttributes().OfType().Any() ||
                                   context.ApiDescription.ActionAttributes().OfType().Any();
    
                if (hasAuthorize)
                {
                    operation.Responses.Add("401", new Response { Description = "Unauthorized" });
                    operation.Responses.Add("403", new Response { Description = "Forbidden" });
    
                    operation.Security = new List>> {
                    new Dictionary>
                    {
                        //{"oauth2", _scopes},
                        {"jwt", _scopes }
                    }
                };
                }
            }
        }
    }
    

    Usage:

            services.AddMySwagger(
                new ApiVersion(1, 0),
                __description => new Info { Title = $"API v{__description.ApiVersion}", Version = __description.ApiVersion.ToString() },
                Configuration.GetValue("Authentication:Authority"),
                new Dictionary { { Configuration.GetValue("Authentication:Scope"), "Partnership API" } }
            );
    

提交回复
热议问题