【问题标题】:protect asp.net web api 2 project with identity server 4使用身份服务器 4 保护 asp.net web api 2 项目
【发布时间】:2021-10-01 06:46:03
【问题描述】:

我有一个带有 .Net framework 4.8 的 asp.net web api 2 项目和一个集中的 Identity Server 4 项目。我想在我的 web api 2 项目中验证从 IS4 生成的 jwt/access 令牌。我可以理解它是一个重复的问题,但不知何故我找不到任何合适的帮助,我不确定缺少什么。我在 web api 项目中使用IdentityServer3.AccessTokenValidation 进行令牌验证。

Startup.cs

using IdentityServer3.AccessTokenValidation;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(WebApplicationApiNew.Startup))]

namespace WebApplicationApiNew
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority = "https://localhost:44373",
                RequiredScopes = new[] { "api1" },
            });
        }
    }
}

使用有效的 JWT 不记名令牌调用此 API 仍会出现 401:

        [Authorize]
        [HttpPost]
        public String GetName1()
        {
            if (User.Identity.IsAuthenticated)
            {
                var identity = User.Identity as ClaimsIdentity;
                if (identity != null)
                {
                    IEnumerable<Claim> claims = identity.Claims;
                }
                return "Valid";
            }
            else
            {
                return "Invalid";
            }
        }

错误详情:

2021-07-24 20:41:25.4133|DEBUG|Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationMiddleware|Authentication failed
Microsoft.IdentityModel.Tokens.SecurityTokenInvalidAudienceException: IDX10214: Audience validation failed. Audiences: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'. Did not match: validationParameters.ValidAudience: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]' or validationParameters.ValidAudiences: '[PII is hidden. For more details, see https://aka.ms/IdentityModel/PII.]'.
   at Microsoft.IdentityModel.Tokens.Validators.ValidateAudience(IEnumerable`1 audiences, SecurityToken securityToken, TokenValidationParameters validationParameters)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateAudience(IEnumerable`1 audiences, JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateTokenPayload(JwtSecurityToken jwtToken, TokenValidationParameters validationParameters)
   at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)
   at Microsoft.Owin.Security.Jwt.JwtFormat.Unprotect(String protectedText)
   at Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationHandler.<AuthenticateCoreAsync>d__3.MoveNext()

【问题讨论】:

    标签: jwt asp.net-web-api2 identityserver4 owin identityserver3


    【解决方案1】:

    错误显示:

    IDX10214: Audience validation failed
    

    如果您的 JWT 令牌包含“aud”声明,则身份验证中间件 正在尝试验证受众声明,但您的选项中没有指定受众。您可以尝试以下方法之一吗:

    1. 在选项中设置受众:

      Audience = "[你的观众]"

    2. 在选项中禁用受众验证:

      TokenValidationParameters.ValidateAudience = false;

    有关详细信息,请参阅身份服务器文档:

    https://docs.identityserver.io/en/latest/topics/apis.html
    

    【讨论】:

      【解决方案2】:

      我找到了解决问题的方法。 IS3 要求 aud 声明(在 url 中带有 /resources)出现在 jwt/access 令牌中以验证令牌。但另一方面,默认情况下 IS4 已停止发出 aud 声明。因此,我们需要明确设置 IS4 服务器以发出 aud 声明,以支持使用 IdentityServer3.AccessTokenValidation 进行旧式/旧访问令牌验证。

                  services.AddIdentityServer(options =>
                  {
                      ...
                      options.EmitStaticAudienceClaim = true; // <- for older access token validation
                  })
                      .AddDeveloperSigningCredential()
                      .AddInMemoryPersistedGrants()
                      .AddInMemoryIdentityResources(Config.GetIdentityResources())
                      ...
      

      【讨论】:

        猜你喜欢
        • 2017-03-12
        • 2021-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-17
        • 2016-07-17
        • 1970-01-01
        • 2017-07-26
        相关资源
        最近更新 更多