如何验证JWT令牌

时间:2018-05-06 21:49:49

标签: c# security jwt

我试图使用JWT令牌。我设法生成了一个有效的JWTTokenString并在JWT debugger上对其进行了验证,但我却无法在.Net中验证令牌。这是我到目前为止的代码:

class Program {

    static string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";

    static void Main(string[] args) {
        var stringToken = GenerateToken();
        ValidateToken(stringToken);
    }

    private static string GenerateToken() {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));

        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var header = new JwtHeader(credentials);

        var payload = new JwtPayload {
           { "some ", "hello "},
           { "scope", "world"},
        };

        var secToken = new JwtSecurityToken(header, payload);
        var handler = new JwtSecurityTokenHandler();

        return handler.WriteToken(secToken);

    }

    private static bool ValidateToken(string authToken) {
        var tokenHandler = new JwtSecurityTokenHandler();
        var validationParameters = GetValidationParameters();

        SecurityToken validatedToken;
        IPrincipal principal = tokenHandler.ValidateToken(authToken, validationParameters, out validatedToken);
        Thread.CurrentPrincipal = principal;
        return true;
    }

    private static TokenValidationParameters GetValidationParameters() {
        return new TokenValidationParameters() {
            //NOT A CLUE WHAT TO PLACE HERE
        };
    }
}

我想要的只是一个接收令牌并根据其有效性返回true或false的函数。从研究中我发现人们使用IssuerSigningToken来分配验证密钥。但是当我尝试使用它时,它似乎并不存在。任何人都可以帮我验证令牌吗?

2 个答案:

答案 0 :(得分:12)

您必须使用相同的密钥将令牌验证为用于生成令牌的令牌。此外,您还需要禁用某些验证,例如到期,发布者和审核,因为您生成的令牌不具备这些信息(或者您可以添加这些信息)。这是一个有效的例子:

class Program
{
    static string key = "401b09eab3c013d4ca54922bb802bec8fd5318192b0a75f201d8b3727429090fb337591abd3e44453b954555b7a0812e1081c39b740293f765eae731f5a65ed1";

    static void Main(string[] args)
    {
        var stringToken = GenerateToken();
        ValidateToken(stringToken);
    }

    private static string GenerateToken()
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var secToken = new JwtSecurityToken(
            signingCredentials: credentials,
            issuer: "Sample",
            audience: "Sample",
            claims: new[]
            {
                new Claim(JwtRegisteredClaimNames.Sub, "meziantou")
            },
            expires: DateTime.UtcNow.AddDays(1));

        var handler = new JwtSecurityTokenHandler();
        return handler.WriteToken(secToken);
    }

    private static bool ValidateToken(string authToken)
    {
        var tokenHandler = new JwtSecurityTokenHandler();
        var validationParameters = GetValidationParameters();

        SecurityToken validatedToken;
        IPrincipal principal = tokenHandler.ValidateToken(authToken, validationParameters, out validatedToken);
        return true;
    }

    private static TokenValidationParameters GetValidationParameters()
    {
        return new TokenValidationParameters()
        {
            ValidateLifetime = false, // Because there is no expiration in the generated token
            ValidateAudience = false, // Because there is no audiance in the generated token
            ValidateIssuer = false,   // Because there is no issuer in the generated token
            ValidIssuer = "Sample",
            ValidAudience = "Sample",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)) // The same key as the one that generate the token
        };
    }
}

答案 1 :(得分:0)

验证 Jwt 中间件类中的令牌,在每个授权请求中调用方法

JwtMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly TokenValidationParameters _tokenValidationParams;
        public JwtMiddleware(RequestDelegate next, TokenValidationParameters 
        tokenValidationParams)
        {
            _next = next;
            _tokenValidationParams = tokenValidationParams;
        }

    

    public async Task Invoke(HttpContext context)
            {
            try{
                var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
    
                var jwtTokenHandler = new JwtSecurityTokenHandler();
                // Validation 1 - Validation JWT token format
                var tokenInVerification = jwtTokenHandler.ValidateToken(token, _tokenValidationParams, out var validatedToken);
    
                if (validatedToken is JwtSecurityToken jwtSecurityToken)
                {
                    var result = jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase);
    
                    if (result == false)
                    {
                        Error Invalid = new Error()
                        {
                            Success = false,
                            Errors = "Token is Invalid"
                        };
    
                        context.Items["Error"] = Invalid;
                    }
                }
           }
           catch (Exception ex)
            {
                Error Invalid = new Error()
                {
                    Success = false,
                    Errors = "Token does not match or may expired."
                };
                context.Items["Error"] = Invalid ; // userService.GetById(userId);
            }
                await _next(context);
        }
    }