首页 > 解决方案 > 带有 Identity Server 4 的 Web API 2 Framework 4.x 中的访问令牌验证

问题描述

希望有人能指出我正确的方向,我需要在我的 api 中验证身份服务器 4 发出的访问令牌。

API 中已设置授权属性。

从服务器正确检索访问令牌,但是当将访问令牌传递给请求时,我收到 401 Unauthorized 错误,并且没有任何处理请求被拒绝。我正在使用 IdentityServer3.AccessTokenValidation nuget 包。

我注意到对于 AccessTokenValidation 的 v4,您可以设置 RequireHttpsMetadata = false 但我看不到在 v3 中如何设置。

这是最好的方法还是我应该寻找另一个方向?

public void ConfigureAuth(IAppBuilder app)
{

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = "Cookies",
    });

    JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, 
    string> 
    ();

    app.UseIdentityServerBearerTokenAuthentication
    (new IdentityServerBearerTokenAuthenticationOptions
    {
        Authority = "http://localhost:5000",
        RequiredScopes = new[] { "api2" },
    });
}

谢谢

标签: oauth-2.0asp.net-web-api2identityserver4identityserver3

解决方案


您需要删除UseCookieAuthentication并使用UseIdentityServerBearerTokenAuthentication.

使用部分

using System.IdentityModel.Tokens.Jwt;
using IdentityServer3.AccessTokenValidation;
using Microsoft.Owin;
using Owin;
using System.Net;

下面的配置适用于我使用 .Net 4.7 和dentityServer3.Contrib.AccessTokenValidation nuget 包

public void ConfigureAuth(IAppBuilder app)
{
    JwtSecurityTokenHandler.DefaultInboundClaimFilter.Clear();
    JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
    JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

    app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
    {
        Authority = "http://localhost:5000",
        RequireHttps = false, // For development
        RequiredScopes = new List<string> { "openid", "profile", "address", "roles", "offline_access" },            
    });
}

使用的 nuget 包

Install-Package IdentityModel -Version 3.10.10
Install-Package IdentityServer3.Contrib.AccessTokenValidation -Version 4.0.36
Install-Package Microsoft.IdentityModel.Tokens -Version 5.3.0
Install-Package System.IdentityModel.Tokens.Jwt -Version 5.3.0
Install-Package Microsoft.IdentityModel.Protocols.OpenIdConnect -Version 5.3.0
Install-Package Microsoft.IdentityModel.Protocols -Version 5.3.0
Install-Package Microsoft.IdentityModel.Logging -Version 5.3.0
Install-Package Microsoft.IdentityModel.JsonWebTokens -Version 5.3.0

推荐阅读