Identity Server 4 的 API 授权不断返回 401 Unauthorized

Jac*_*rst 5 openid-connect asp.net-core identityserver4 jwt-auth

我正在使用 Identity Server 4 .Net Core 3,如果我在启动时使用标准配置,我的 API 端点不会验证访问令牌,我不断收到 401 Unauthorized,但是当我使用授权属性在控制器中设置身份验证方案时,我可以使用相同的令牌成功访问我的端点...

[Route("api/[controller]")]
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[ApiController]
public class MyWebAPiControllerController : ControllerBase
{
.......
Run Code Online (Sandbox Code Playgroud)

这是我的身份服务器配置:

//API resource       
public IEnumerable<ApiResource> Apis()
{
        var resources = new List<ApiResource>();

        resources.Add(new ApiResource("identity", "My API", new[] { JwtClaimTypes.Subject, JwtClaimTypes.Email, JwtClaimTypes.Role, JwtClaimTypes.Profile }));

        return resources;
}
Run Code Online (Sandbox Code Playgroud)

我的客户端配置:

public IEnumerable<Client> Clients()
    {

        var Clients = new List<Client>();

        Clients.Add(new Client
        {
            ClientId = "client",
            ClientSecrets = { new Secret(_securityConfig.Secret.Sha256()) },

            AllowedGrantTypes = GrantTypes.ClientCredentials,
            // scopes that client has access to
            AllowedScopes = { "identity" }
        });

        Clients.Add(new Client
        {
            ClientId = "mvc",
            ClientName = "MVC Client",

            AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
            //RequirePkce = true,
            ClientSecrets = { new Secret(_securityConfig.Secret.Sha256()) },
            RequireConsent = false,
            RedirectUris = _securityConfig.RedirectURIs,
            FrontChannelLogoutUri = _securityConfig.SignoutUris,
            PostLogoutRedirectUris = _securityConfig.PostLogoutUris,
            AllowOfflineAccess = true,
            AllowAccessTokensViaBrowser = true,
            AllowedScopes = new List<string>
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    IdentityServerConstants.StandardScopes.OfflineAccess,
                    "identity"
                }

        });

        return Clients;
    } 
Run Code Online (Sandbox Code Playgroud)

我的 API 配置

 services.AddAuthentication("Bearer")
            .AddJwtBearer("Bearer", options =>
            {
                options.Authority = _securityConfig.Authority;
                options.RequireHttpsMetadata = false;

                options.Audience = "identity";
            });
Run Code Online (Sandbox Code Playgroud)

最后是我的 Web 应用程序、OIDC 配置以及我如何获取访问令牌:

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = "oidc";
        }).AddCookie(options =>
            {
                options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
                options.Cookie.Name = "identity_cookie";
            })
        .AddOpenIdConnect("oidc", options =>
        {
            options.Events = new OpenIdConnectEvents
            {
                OnUserInformationReceived = async ctx =>
                {
                    //Get Token here and assign to Cookie for use in Jquery
                    ctx.HttpContext.Response.Cookies.Append("bearer_config", ctx.ProtocolMessage.AccessToken);
                }
            };

            options.Authority = _securityConfig.Authority;
            options.RequireHttpsMetadata = false;

            options.ClientId = "mvc";
            options.ClientSecret = _securityConfig.Secret;
            options.ResponseType = "code id_token";
            options.SaveTokens = true;


            options.Scope.Clear();
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.Scope.Add("email");
            options.Scope.Add("identity");
            options.Scope.Add("offline_access");

            options.ClaimActions.MapAllExcept("iss", "nbf", "exp", "aud", "nonce", "iat", "c_hash");

            options.GetClaimsFromUserInfoEndpoint = true;
            //options.SaveTokens = true;

            options.TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = JwtClaimTypes.Name,
                RoleClaimType = JwtClaimTypes.Role,
            };


        });
Run Code Online (Sandbox Code Playgroud)

关于为什么我不断收到 401 Unauthorized 的任何想法?

小智 7

根据所描述的行为,我认为这可能与中间件配置有关,更具体地说是与中间件的顺序有关。但我无法确定,因为 Startup.Configure 在问题中不可用。

幸运的是,雅克可以确认问题确实出在订单上。正如评论中提到的:

app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
Run Code Online (Sandbox Code Playgroud)

这里的问题是用户首先被授权(UseAuthorization),然后被验证(UseAuthentication)。因此,用户永远无法获得授权,因为此时用户是未知的(匿名)。但稍后,当属性得到验证时,用户就已知了。这就解释了为什么它有效。

为了解决这个问题,必须切换语句。首先对用户进行认证(识别用户,用户是谁?),然后对用户进行授权:

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
Run Code Online (Sandbox Code Playgroud)

该顺序在文档中进行了描述。