【问题标题】:Access Token Validation in Web API 2 Framework 4.x with Identity Server 4带有 Identity Server 4 的 Web API 2 Framework 4.x 中的访问令牌验证
【发布时间】:2019-05-07 18:54:26
【问题描述】:

希望有人能指出正确的方向,我需要在我的 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.0 asp.net-web-api2 identityserver4 identityserver3


【解决方案1】:

您需要删除 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

【讨论】:

  • 我收到错误 - TypeLoadException:无法加载类型 System.IdentityModel.Tokens.TokenValidationParameters。你能分享你正在使用的 OWIN 和 IdenityModel 包吗
  • @Dibzmania 确保您已安装 Microsoft.IdentityModel.Tokens -Version 5.3.0 软件包,我还在答案中添加了更多详细信息
  • 是的,我解决了这个问题。谢谢
猜你喜欢
  • 2020-12-07
  • 1970-01-01
  • 2020-02-06
  • 2018-02-21
  • 2018-03-08
  • 2018-06-01
  • 2017-06-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多