Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct use of JwtTokens in C#

Tags:

c#

jwt

claims

I'm playing a with JwtTokens and can't make them work properly. I'm using http://www.nuget.org/packages/System.IdentityModel.Tokens.Jwt/ for it. I know the code is a mess but is just to show what I'm trying to do. The problem is that I want the JwtTokenHandler to fail the validation because of the lifetime.

var key = "5A0AB091-3F84-4EC4-B227-0834FCD8B1B4";
var domain = "http://localhost";
var allowedAudience = "http://localhost";
var signatureAlgorithm = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256";
var digestAlgorithm = "http://www.w3.org/2001/04/xmlenc#sha256";
var issuer = "self";
var securityKey = System.Text.Encoding.Unicode.GetBytes(key);
var inMemorySymmetricSecurityKey = new InMemorySymmetricSecurityKey(securityKey);

var now = DateTime.UtcNow;
var expiry = now.AddSeconds(1);
var tokenHandler = new JwtSecurityTokenHandler();
var claimsList = new List<Claim>()
{
    new Claim(ClaimTypes.Name, "user"),
    new Claim(ClaimTypes.Webpage, allowedAudience),
    new Claim(ClaimTypes.Uri, domain),                
    new Claim(ClaimTypes.Expiration,expiry.Ticks.ToString())
};
var roles = new List<string>() { "admin" };
claimsList.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));

var identity = new GenericIdentity("user");

var tokenDescriptor = new SecurityTokenDescriptor
{
    Subject = new ClaimsIdentity(identity, claimsList),
    TokenIssuerName = issuer,
    AppliesToAddress = allowedAudience,
    Lifetime = new Lifetime(now, expiry),
    SigningCredentials = new SigningCredentials(inMemorySymmetricSecurityKey, signatureAlgorithm, digestAlgorithm),
};

var token = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));

var validationParameters = new TokenValidationParameters()
{
    ValidIssuer = issuer,
    ValidAudience = allowedAudience,
    IssuerSigningToken = new BinarySecretSecurityToken(securityKey)
};

Thread.Sleep(2000);
try
{
    SecurityToken securityToken;
    tokenHandler.ValidateToken(token, validationParameters, out securityToken);
    Console.WriteLine("OK");
}
catch (Exception e)
{
    Console.WriteLine("Error {0}", e.Message);
}

Isn't this suppose to fail since I'm waiting 2 seconds? It fails if I change the issuer of the ValidationTokenParameter to "x"...

like image 326
dariogriffo Avatar asked Apr 04 '15 11:04

dariogriffo


People also ask

What is the correct format of JWT token?

Figure 1 shows that a JWT consists of three parts: a header, payload, and signature. The header typically consists of two parts: the type of the token, which is JWT, and the algorithm that is used, such as HMAC SHA256 or RSA SHA256. It is Base64Url encoded to form the first part of the JWT.

Where do I put JWT tokens?

A JWT needs to be stored in a safe place inside the user's browser. If you store it inside localStorage, it's accessible by any script inside your page.

Why we use JWT token in C#?

JWT authentication is a standard way for protecting APIs - it's adept at verifying the data that's transmitted over the wire between APIs and the clients that consume the APIs. You can even safely pass claims between the communicating parties as well.

What is JWT token how it works?

Secure: JWTs are digitally signed using either a secret (HMAC) or a public/private key pair (RSA or ECDSA) which safeguards them from being modified by the client or an attacker. Stored only on the client: You generate JWTs on the server and send them to the client. The client then submits the JWT with every request.

What do you put in a JWT token?

Unserialized JWTs have two main JSON objects in them: the header and the payload . The header object contains information about the JWT itself: the type of token, the signature or encryption algorithm used, the key id, etc. The payload object contains all the relevant information carried by the token.

What are the three types of claims uses in JWT?

There are three types of claims: "registered," "public," and "private." You can find the list of registered and public claims in the official IANA Registry. You can also add any other custom claim to a JWT; these are known as "private claims."


1 Answers

Found the issue. The validation parameters have a default clock skew of 5 minutes

/// <summary>
/// Default for the clock skew.
/// 
/// </summary>
/// 
/// <remarks>
/// 300 seconds (5 minutes).
/// </remarks>
public static readonly TimeSpan DefaultClockSkew;

Setting that to 0 make this work. Still don't understand why the skew is 5 minutes, if I set the expiry at some point!!!

like image 52
dariogriffo Avatar answered Oct 29 '22 13:10

dariogriffo