Search code examples
.net

Identify user based upon JWT


I have a web application using .NET Identity which is using the standard (cookie based) authentication.

I have a separate controller for a mobile app that uses JWT authentication.

Both of these are set up to be used in the middleware and all works fine.

The mobile app (using .NET MAUI) can open URLs in the system browser. I want to find a way to automatically log the user into the web app (which uses the cookie scheme) when they open a certain page.

My thinking is, if I can open a URL and pass the token in a querystring parameter ?token={token} I can then identify the Identity User and use that to perform the standard _signinManager.SignInAsync(User).

But I don't know how to lookup the Identity User using the JWT string obtained from the querystring.

Something like _userManager.FindByJWT(jwt) or similar.

Any ideas?


Solution

  • This code will validate the jwt token using whatever key you used to create it. Then extract the userId from the claim.

    var tokenHandler = new JwtSecurityTokenHandler();
    var validationParameters = new TokenValidationParameters
    {
        ValidIssuer = "SomeIssuer",
        ValidAudience = "SomeAudience",
        IssuerSigningKey = GetKey(), // The key used for signing the jwt token
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true
    };
    
    try
    {
        tokenHandler.ValidateToken(token, validationParameters, out var validatedToken);
        
        var jwtToken = validatedToken as JwtSecurityToken;
        var userIdClaim = jwtToken.Claims.First(claim => claim.Type == "userId"); // I'm guessing here and it will depend on how your token is constructed.
        var userId = userIdClaim.Value;
    }
    catch (SecurityTokenException)
    {
        // Not valid
    }