簡體   English   中英

swagger asp..net core 3.1的隱式承載流

[英]Implicit Bearer flow for swagger asp..net core 3.1

有沒有辦法自動將不記名令牌放入 Swagger 中的每個請求? 我不想在應該與身份交互的地方使用 oauth 隱式流。

我想為我的 api 提供一個端點,它可以獲取訪問令牌並自動將其放入每個請求中。

在您的 startup.s 類中:

// prevent from mapping "sub" claim to nameidentifier.
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub");

var identityUrl = configuration.GetValue<string>("IdentityUrl");

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
    options.Authority = identityUrl;
    options.RequireHttpsMetadata = false;
    options.Audience = "demo_api";
});

SwaggerGen

    services.AddSwaggerGen(options =>
    {
      ...
        options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
       {
            Type = SecuritySchemeType.OAuth2,
            Flows = new OpenApiOAuthFlows
            {
                Implicit = new OpenApiOAuthFlow
                {
                    AuthorizationUrl = new Uri($"{configuration.GetValue<string>("IdentityUrl")}/connect/authorize"),
                    TokenUrl = new Uri($"{configuration.GetValue<string>("IdentityUrl")}/connect/token"),
                    Scopes = new Dictionary<string, string>()
                    {
                        { "api1", "Demo API - full access" }
                    }
                }
            }
        });

操作過濾器

options.OperationFilter<AuthorizeCheckOperationFilter>();

實施

public class AuthorizeCheckOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any() ||
                           context.MethodInfo.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any();

        if (!hasAuthorize) return;

        var unauthorizedHashCode = HttpStatusCode.Unauthorized.GetHashCode().ToString();
        var unauthorizedDescription = HttpStatusCode.Unauthorized.ToString();

        var forbiddenHashCode = HttpStatusCode.Forbidden.GetHashCode().ToString();
        var forbiddenDescription = HttpStatusCode.Forbidden.ToString();

        operation.Responses.TryAdd(unauthorizedHashCode, new OpenApiResponse { Description = unauthorizedDescription });
        operation.Responses.TryAdd(forbiddenHashCode, new OpenApiResponse { Description = forbiddenDescription });

        var oAuthScheme = new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
        };

        operation.Security = new List<OpenApiSecurityRequirement>
        {
            new OpenApiSecurityRequirement
            {
                [ oAuthScheme ] = new [] { "api1" }
            }
        };

    }
}

用這個

// Keep both UseAuthentication and UseAuthorization IN THIS ORDER
app.UseAuthentication();
app.UseAuthorization();

使用 Swagger

app.UseSwagger(c =>
        {
            c.RouteTemplate = "swagger/{documentName}/swagger.json";
        });
        app.UseSwaggerUI(s =>
        {
            s.SwaggerEndpoint("/swagger/v1/swagger.json", "Your awesome project name");

            s.OAuthAppName("My API - Swagger");
            s.OAuthClientId("client");

            // Should match the client RedirectUrl in the IdentityServer
            s.OAuth2RedirectUrl("https://localhost:5001/swagger/oauth2-redirect.html");
        });

您的控制器

[Authorize]
[ApiController]
[Route("api/[controller]")] // TODO: Take care of the versioning
public class IndentityController : ControllerBase
{
    ...

現在在 IdentityServer 項目中。 Api資源:

public static IEnumerable<ApiResource> GetApiResources()
    {
        return new List<ApiResource>
        {
            new ApiResource("api1", "My API")
        };
    }

最后,您的客戶端應如下所示:

new Client
{
    ClientId = "client",
    AllowedGrantTypes = GrantTypes.Implicit,
    RedirectUris = { "https://localhost:5001/swagger/oauth2-redirect.html" },
    AllowedScopes = { "api1" },
    AllowAccessTokensViaBrowser = true,
    RequireConsent = false
}

如需完整的源代碼,請查看eShopOnContainers 存儲庫

祝你好運 :)

下一個代碼對我有用

services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v2", new Microsoft.OpenApi.Models.OpenApiInfo
            {
                Version = "v2",
                Title = "PRJ API",
                Description = "PRJ Web API",
            });

            if (oktaIssuer != null)
            {
                c.AddSecurityDefinition("Okta", new OpenApiSecurityScheme
                {
                    Type = SecuritySchemeType.OAuth2,
                    Scheme = "Bearer",
                    In = ParameterLocation.Header,
                    Name = "Authorization",
                    Flows = new OpenApiOAuthFlows
                    {
                        Implicit = new OpenApiOAuthFlow
                        {
                            AuthorizationUrl = new Uri($"{oktaIssuer}/v1/authorize"),
                            Scopes = new Dictionary<string, string>
                            {
                                { "profile", "Access profile" },
                                { "email", "Email"},
                                { "openid", "OpenID"}
                            }
                        }
                    }
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Okta" },
                            Scheme = "oauth2",
                            Name = "Bearer",
                            In = ParameterLocation.Header
                        },
                       
                        new string[] {}
                    }
                });
                c.OperationFilter<AuthorizeCheckOperationFilter>();
            }

這些字符串也必須相同! AddSecurityDefinition&AddSecurityRequirement

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM