【问题标题】:Custom SecurityTokenValidator works but still unauthorized自定义 SecurityTokenValidator 有效但仍未经授权
【发布时间】:2019-07-06 00:57:24
【问题描述】:

我在使用 JWT 验证的 dotnet core 中遇到了一些问题。

我创建了一个自定义验证器,而不是验证令牌,它将被转发到另一个 API 并返回令牌。这很好用,但是,我不断收到响应:未经授权。

这是我的验证器,很简单,它验证令牌,如果得到响应,应该没问题。

public class JwtValidator : ISecurityTokenValidator
{
    AuthenticationClient authClient;

    public JwtValidator(AuthenticationClient authClient)
    {
        this.authClient = authClient;
    }

    public bool CanValidateToken => true;

    public int MaximumTokenSizeInBytes { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

    public bool CanReadToken(string securityToken)
    {
        return true;
    }

    public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
    {
        validatedToken = null;

        //your logic here
        var response = authClient.Validate(securityToken);
        //assuming response will contain info about the user

        if (response == null)
            throw new SecurityTokenException("invalid");

        validatedToken = response.Result;

        return new ClaimsPrincipal(new ClaimsIdentity(response.Result.Claims));
}

没有抛出异常,令牌有效,正在返回声明。

在 Startup.cs 我有以下代码:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.SecurityTokenValidators.Clear();
            options.SecurityTokenValidators.Add(new JwtValidator(authClient));
        });

当我将日志记录添加到 JwtValidator 时,我确实得到了日志,因此该函数似乎被正确调用。但 API 不断返回“未授权”。

【问题讨论】:

  • 你最后搞定了吗?我现在不确定要以 validatedToken 的形式返回什么,所以我推出了 new JwtSecurityToken() 和一堆其他变体。然后我得到 401 bagger from you untrustworthy bum 我强烈怀疑这与此有关。或者可能使用 ClaimsPrincipal 实例。否则,其他一切似乎都可以正常工作......

标签: c# authentication .net-core jwt


【解决方案1】:

我在 .net core 5 中实现自定义 JWT 处理程序的方式是继承自 JwtSecurityTokenHandler 而不是 ISecurityTokenValidator(这是 SecurityTokenValidator 的基本接口)。然后为了验证我调用的令牌

var claimsPrincipal = base.ValidateToken(token, validationParameters, out validatedToken);

直接返回 ClaimsPrinciple。 在您的代码中,我怀疑 AuthenticationClient 可能是问题所在。 下面是我的验证码。

public class JwtValidator : JwtSecurityTokenHandler
{
    // Define constructor and other custom attributes   
   public ClaimsPrincipal ValidateToken(string securityToken, 
   TokenValidationParameters validationParameters, 
   out SecurityToken validatedToken)
    {
         var claimsPrincipal = base.ValidateToken(token, validationParameters, out validatedToken);
         return claimsPrincipal;
    }
}

【讨论】:

    猜你喜欢
    • 2021-03-07
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 2019-06-29
    • 2017-07-03
    • 1970-01-01
    相关资源
    最近更新 更多