JWT Authentication and Swagger with .Net core 3.0

后端 未结 6 865
我在风中等你
我在风中等你 2020-12-25 12:31

I am developing some Web Api with .Net core 3.0 and want to integrate it with SwashBuckle.Swagger. It is working fine, but when I add JWT authentication, it does not work as

6条回答
  •  误落风尘
    2020-12-25 12:55

    Here's a solution updated for Swashbuckle.AspNetCore 5.3.2, integrated with IdentityServer4, with an API secured using a Bearer token.

    In ConfigureServices() method:

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
                options.AddSecurityDefinition("Bearer", SecuritySchemes.BearerScheme(Configuration));
                options.AddSecurityRequirement(new OpenApiSecurityRequirement()
                {
                    { SecuritySchemes.OAuthScheme, new List() }
                });
            });
    

    In Configure() method:

            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/My.Api/swagger/v1/swagger.json", "My API V1");
                options.OAuthClientId(Clients.TestClient);
                options.OAuthAppName("My Api - Swagger");
                options.OAuthClientSecret(Configuration["TestClientSecret"]);
            });
    
    internal static class SecuritySchemes
    {
        public static OpenApiSecurityScheme BearerScheme(IConfiguration config) => new OpenApiSecurityScheme
        {
            Type = SecuritySchemeType.OAuth2,
            Description = "Standard authorisation using the Bearer scheme. Example: \"bearer {token}\"",
            In = ParameterLocation.Header,
            Name = "Authorization",
            Scheme = "Bearer",
            OpenIdConnectUrl = new System.Uri($"{config["TokenServerUrl"]}.well-known/openid-configuration"),
            BearerFormat = "JWT",
            Flows = new OpenApiOAuthFlows
            {
                Password = new OpenApiOAuthFlow
                {
                    AuthorizationUrl = new System.Uri($"{config["TokenServerUrl"]}connect/authorize"),
                    Scopes = new Dictionary
                        {
                            { Scopes.Api, "My Api" }
                        },
                    TokenUrl = new System.Uri($"{config["TokenServerUrl"]}connect/token")
                }
            }
        };
    
        public static OpenApiSecurityScheme OAuthScheme => new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference
            {
                Type = ReferenceType.SecurityScheme,
                Id = "Bearer"
            },
            Scheme = "oauth2",
            Name = "Bearer",
            In = ParameterLocation.Header,
    
        };
    }
    

提交回复
热议问题