Created
April 8, 2020 02:56
-
-
Save mrnkr/3a369aed7268be9ca7f2d44e34c17343 to your computer and use it in GitHub Desktop.
This is how I create jwt tokens in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Extensions.Configuration; | |
using Microsoft.IdentityModel.Tokens; | |
using System; | |
using System.IdentityModel.Tokens.Jwt; | |
using System.Security.Claims; | |
using System.Text; | |
namespace TwoDrive.Core | |
{ | |
public class TokenService | |
{ | |
private IConfiguration Config { get; } | |
public TokenService(IConfiguration config) | |
{ | |
Config = config; | |
} | |
public string CreateTokenForUser(string uid) | |
{ | |
var claims = new[] | |
{ | |
new Claim(JwtRegisteredClaimNames.Sub, uid), | |
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) | |
}; | |
var signingKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Config["Jwt:SigningKey"])); | |
var expiryInMinutes = Convert.ToInt32(Config["Jwt:ExpiryInMinutes"]); | |
var token = new JwtSecurityToken( | |
issuer: Config["Jwt:Site"], | |
audience: "access", | |
expires: DateTime.UtcNow.AddMinutes(expiryInMinutes), | |
signingCredentials: new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256Signature), | |
claims: claims | |
); | |
return new JwtSecurityTokenHandler().WriteToken(token); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And this is how I validate them