带有 JWT 身份验证层的 ASP.NET Core 5 Web API 的 Swagger 配置

问题描述

我正在尝试在具有 JWT 身份验证层的 Web API 中设置 Swagger。我让它在 Postman 中工作得很好,但似乎无法让我的招摇设置来适应它。

我可以点击我的 IS4 登录页面并成功进行身份验证(获得成功弹出窗口并且我的“授权”按钮上有一个锁定),但是当我点击我的端点时,它给了我一个 401。假设这是因为它不是' t 将令牌存储在某处,但不确定?

上下文:

Swagger 服务

services.AddSwaggerGen(config =>
            {
                config.SwaggerDoc(
                    "v1",new OpenApiInfo
                    {
                        Version = "v1",Title = "MySwaggerDoc",Description = "This is my swagger doc",Contact = new OpenApiContact
                        {
                            Name = "Paul",Email = "[email protected]",Url = new Uri("https://www.thisispaulswebsite.com"),},});

config.AddSecurityDefinition("oauth2",new OpenApiSecurityScheme
                {
                    Type = SecuritySchemeType.OAuth2,Flows = new OpenApiOAuthFlows
                    {
                        AuthorizationCode = new OpenApiOAuthFlow
                        {
                            AuthorizationUrl = new Uri("https://localhost:5010/connect/authorize"),TokenUrl = new Uri("https://localhost:5010/connect/token"),Scopes = new Dictionary<string,string>
                            {
                                { "patients.read","CanReadPatient" },}
                        }
                    }
                });
            });

Swagger 应用:

app.UseSwagger();

app.UseSwaggerUI(config =>
        {
            config.SwaggerEndpoint("/swagger/v1/swagger.json","");

            config.OAuthClientId("swagger");
            config.OAuthClientSecret("secret");
            config.OAuthAppName("Swagger UI for demo_api");
            config.OAuthUsePkce();
        });

我的 IS4 客户:

new Client
    {
        ClientId = "swagger",ClientName = "Swagger UI for demo_api",ClientSecrets = {new Secret("secret".Sha256())},// change me!

        AllowedGrantTypes = GrantTypes.Code,RequirePkce = true,RequireClientSecret = false,RedirectUris = {"https://localhost:5000/swagger/oauth2-redirect.html"},// If you have a base path for your Swagger UI,then also include it in your redirect URI (i.e. if you have the Swagger UI on /swagger,your redirect URI should be /swagger/oauth2-redirect.html). 
        AllowedCorsOrigins = {"https://localhost:5000"},AllowedScopes = { "patients.read","patients.add","patients.update","patients.delete","openid","profile" },new Client
    {
        ClientId = "postman patient",ClientName = "postman UI for demo_api",RedirectUris = { "https://oauth.pstmn.io/v1/callback" },}

我的邮递员工作电话:

working postman call

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)