JWT 令牌未在远程服务器上验证,无法匹配 'kid' 错误

JWT token not validating on remote server , Unable to match 'kid' Errror

我正在使用 asp.net 核心和 openiddict ,为了授权我正在使用 jwtmiddleware

 app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
               RequireHttpsMetadata = false,
               Authority= "http://localhost"
            });

但由于某种原因抛出此错误,我们将不胜感激。

info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerMiddleware[7] Bearer was not authenticated. Failure message: IDX10501: Signature validat ion failed. Unable to match 'kid': '7FG4SQ4TIATESTLI-ZDHTLRYPWIEDU_RA1FVG91D', token: '{"alg":"RS256","typ":"JWT","kid":"7FG4SQ4TIATESTLI-ZDHTLRYPWIEDU_RA1FVG9 1D"}.{"unique_name":"asd","email":"asd","AspNet.Identity.SecurityStamp":"eb93ee4 4-6dbf-41b8-b1d6-157e4aa23ea7","jti":"4f0f5395-e565-4489-8baf-6361d5c4cb94","usa ge":"access_token","confidential":true,"scope":["offline_access","profile","emai l","roles"],"sub":"9125d8c5-5739-4f46-8747-e3423a464969","azp":"firebaseApp","nb f":1466997962,"exp":1466999762,"iat":1466997962,"iss":"http://localhost:5000/"}' . warn: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1] Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.A uthorization.AuthorizeFilter'. warn: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1] Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.A uthorization.AuthorizeFilter'.

  1. 权限应包含您的 OIDC 服务器的基址。您应该指定 Authority URL 和端口(根据令牌信息中的 "iss" 声明,在您的情况下为 5000):

    Authority="http://localhost:5000"
    
  2. 您可以通过设置 ValidateIssuerSigningKey = false 来禁用权限验证。 JwtBearerOptions 包含 属性 TokenValidationParameters,聚合有关验证的设置:

    app.UseJwtBearerAuthentication(new JwtBearerOptions
        {
            ...
            TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = false}
        }
    

如果您使用的是第三方 STS(例如,不是 identityserver 或 Auth0),那么您可以使用 BackChannelHandler 来更轻松地调试来自中间件的 http 结果:

app.UseJwtBearerAuthentication(new JwtBearerOptions() {
    ...
    BackchannelHttpHandler = new BackChannelHandler()
    ...
}

然后

using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace Application.API.Utilities
{
    public class BackChannelHandler : HttpMessageHandler
    {
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpClient client = new HttpClient(new HttpClientHandler(), disposeHandler: false);
            client.DefaultRequestHeaders.Add("Accept", "application/json");
            var res = await client.GetAsync(request.RequestUri);
            return res;
        }
    }   
}

在我的例子中,jwks 和 openid-configuration 端点的默认 return 类型是 text/html 而不是 application/json。通过在从自定义处理程序发出请求时添加一个 Accept header,一切正常。