Search code examples
c#.net-coreasp.net-core-webapiadal

Is there a ready to use "GenerateJwt" method?


I'm using the Microsoft.AspNetCore.Authentication.JwtBearer and System.IdentityModel.Tokens.Jwt for my .NET Core project. In my Startup file I run the configuration setup for the [Authorize] annotation. This works fine for me when I'm generating new tokens with my own method (sample)

public object GenerateToken(Dictionary<string, object> payload)
{
    DateTime tokenExpiresAt = DateTime.Now.AddMilliseconds(1); // From config
    byte[] symmetricKey = Convert.FromBase64String("secret"); // from config
    SymmetricSecurityKey symmetricSecurityKey = new SymmetricSecurityKey(symmetricKey);
    
    SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
    {
        Claims = payload,
        Expires = tokenExpiresAt,
        SigningCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256Signature)
    };
    
    JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
    SecurityToken securityToken = tokenHandler.CreateToken(tokenDescriptor);

    string token = tokenHandler.WriteToken(securityToken);
        
    return new { token, tokenExpiresAt };
}

The validation of a token doesn't need to be implemented because it's done with the [Authorize] annotation. I would like to know if there is a method I can use to generate a token and don't have to code it on my own? I'm storing the generated tokens to a database and also need to return the expiration time.

So yes, the solution above works fine for me but maybe it's redundant :)

Is there a method that takes the token secret, the payload and the time the token will expire? E.g. TokenGenerator.Sign("secret", payload, tokenExpiresAt)?


Solution

  • Microsoft libraries don't support issuing tokens natively, so there's no one command in a Microsoft library like you're looking for. However Microsoft does issue tokens as an identity server using their service azure ad, that would probably be their easiest way. The way you're doing is basically fine if you're just doing that. and not full authentication framework, here's an example of people doing very similar thing to you: https://jasonwatmore.com/post/2019/10/11/aspnet-core-3-jwt-authentication-tutorial-with-example-api

    If you are looking to implement your own complete authentication service that can issue tokens. there are some relatively common 3rd party libraries that will help you not have to reinvent the wheel, one of which is identityserver4: https://identityserver4.readthedocs.io/en/latest/index.html it's a full identity provider solution. another one is openiddict https://devblogs.microsoft.com/aspnet/bearer-token-authentication-in-asp-net-core/