asp.net-web-api - Core 2.0 上的 IdentityServer4 从 API 获取 401(未经授权)

标签 asp.net-web-api access-token identityserver4 asp.net-core-2.0

在尝试迁移到最新版本的 IdentityServer4 和 .NET Core 2 后,我的 Web API 项目突然出现 401 错误。在上周,我做了很多更改,我不知道不知道什么是对什么是错了。

我有一个小型 3 项目解决方案:

  1. IDSRV:https://localhost:44300
  2. 网络应用:https://localhost:44301
  3. API 应用程序:https://localhost:44302

这是我配置 IDSV 的代码,存储在我的数据库中:

public class Config
{
    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
        };
    }

    public static IEnumerable<ApiResource> GetApiResources()
    {
        return new List<ApiResource>
        {
            new ApiResource(){
                Name = "api.oc.com",
                Description = "OC Api",
                Scopes = new[] {new Scope("api.oc.com")}
            }
        };
    }

    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientId = "oc.com",
                ClientName = "OC Website",
                AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                AlwaysIncludeUserClaimsInIdToken = true,                    
                ClientSecrets =
                {
                    new Secret("SomeReallyStrongPassword1!".Sha256())
                },
                RedirectUris = { "https://localhost:44301/signin-oidc" },
                PostLogoutRedirectUris = { "https://localhost:44301/signout-callback-oidc" },
                AllowedScopes =
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    "api.oc.com",
                    "offline_access"
                },                    
                AllowOfflineAccess = true
            }
        };
    }
}

在我的 WEB API Startup.cs 中。我在 ConfigureServices 中有这个。我相信我的 Configure 方法没问题。

        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(o =>
        {
            o.Authority = "https://localhost:44300";
            o.RequireHttpsMetadata = false;
            o.Audience = "api.oc.com";
        });

        services.AddMvcCore()
            .AddAuthorization()
            .AddJsonFormatters();

这将我带到了试图对 WEB API 进行身份验证的 WEB 前端。 我已经尝试过使用访问 token 和 ID token ,但似乎都不起作用。

使用访问 token :

  var accessToken = await HttpContext.GetTokenAsync("access_token");
  var client = new HttpClient();
  client.SetBearerToken(accessToken);
  var result = await client.GetStringAsync("https://localhost:44302/api/text/welcome");

或使用客户端凭据流程:

  var disco = await DiscoveryClient.GetAsync("https://localhost:44300");
  var tokenClient = new TokenClient(disco.TokenEndpoint, "oc.com", "SomeReallyStrongPassword1!");
  var tokenResponse = await tokenClient.RequestClientCredentialsAsync();

  var client = new HttpClient();
  client.SetBearerToken(tokenResponse.AccessToken);
  var result = await client.GetStringAsync("https://localhost:44302/api/text/welcome");

如果有人对此有任何建议,我将非常感谢。看了这么久的安全码,眼珠子都要炸了!哈哈。

谢谢, 迈克·库什纳

最佳答案

经过一些干预......并添加了一个真实的证书,这似乎在我创建了一些策略而不是仅使用 [Authorize] 属性之后起作用。 请注意,我也再次使用 IdentityServer4.AccessTokenValidation。

    public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddAuthorization((options) => {
            options.AddPolicy("MustBeValidUser", policybuilder =>
            {
                policybuilder.RequireAuthenticatedUser();
                policybuilder.Requirements = new[] { new MustBeValidUserRequirement() };
            });
        });
        services.AddSingleton<IAuthorizationHandler, MustBeValidUserHandler>();
        services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
        .AddIdentityServerAuthentication(options =>
        {
            options.Authority = "https://localhost:44300";
            options.RequireHttpsMetadata = true;
            options.ApiName = "api.oc.com";
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();
        app.UseDeveloperExceptionPage();
        app.UseAuthentication();
        app.UseMvc();
    }
}

关于asp.net-web-api - Core 2.0 上的 IdentityServer4 从 API 获取 401(未经授权),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47369524/

相关文章:

c# - 未触发异常过滤器

oauth - OAuth 2.0 访问 token 可以是 JWT 吗?

asp.net-core - 如何在配置文件更新后从 Identity Server 4 刷新声明?

c# - BaseClientService 不包含文件的定义

json - 控制 KeyValuePair<DateTime, long> 键的序列化格式

google-api - Google 刷新 token 会过期吗?

google-api - Google token 刷新返回 "Token has been expired or revoked."

c# - 使用依赖注入(inject)替换 ASP.NET Core 中的 JWT Bearer Options

migration - 将 IdentityServer4 从 v3 迁移到 v4

c# - AngularJS 与 ASP.NET MVC 混淆