1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- using System;
- using System.Configuration;
- using System.IdentityModel.Tokens;
- using System.Security.Claims;
- using System.ServiceModel.Security.Tokens;
- using Newtonsoft.Json;
-
- namespace iiie.Authentication.Business.JWT
- {
- /// <summary>
- /// Token creation class
- /// </summary>
- public static class TokenManager
- {
- /// <summary>
- /// Create signing credentials to sign the token
- /// </summary>
- /// <returns>The credentials</returns>
- private static SigningCredentials CreateSigningCredentials()
- {
- string symmetricKey = ConfigurationManager.AppSettings["CredentialKey"];
- byte[] keybytes = Convert.FromBase64String(symmetricKey);
- SecurityKey securityKey = new InMemorySymmetricSecurityKey(keybytes);
- SigningCredentials signingCredentials =
- new SigningCredentials(securityKey,
- SecurityAlgorithms.HmacSha256Signature,
- SecurityAlgorithms.Sha256Digest);
- return signingCredentials;
- }
-
- /// <summary>
- /// Create a JWT token
- /// </summary>
- /// <param name="username">The user username</param>
- /// <param name="salt">The user salt</param>
- /// <param name="data">Additionnal user data</param>
- /// <returns>The token</returns>
- public static string GetToken(string username, string salt, object data = null)
- {
- var stringValidator = ConfigurationManager.AppSettings["StringValidator"];
- JwtSecurityToken jst = new JwtSecurityToken("urn:" + stringValidator,
- stringValidator,
- new []
- {
- new Claim(ClaimTypes.Name, username),
- new Claim(ClaimTypes.Authentication, salt),
- new Claim(ClaimTypes.UserData, JsonConvert.SerializeObject(data))
- }, null, DateTime.Now.AddDays(1),
- CreateSigningCredentials());
-
- JwtSecurityTokenHandler jh = new JwtSecurityTokenHandler();
- return jh.WriteToken(jst);
- }
-
- public static ClaimsPrincipal ParseToken(string token)
- {
- JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler
- {
- Configuration = new SecurityTokenHandlerConfiguration()
- {
- MaxClockSkew = new TimeSpan(0, 1, 0)
- }
- };
-
- var stringValidator = ConfigurationManager.AppSettings["StringValidator"];
- TokenValidationParameters validationParameters = new TokenValidationParameters()
- {
- RequireSignedTokens = true,
- RequireExpirationTime = true,
- ValidAudience = stringValidator,
- ValidateIssuerSigningKey = true,
- ValidIssuer = "urn:" + stringValidator,
- IssuerSigningToken = new BinarySecretSecurityToken(Convert.FromBase64String(ConfigurationManager.AppSettings["CredentialKey"]))
- };
-
- SecurityToken validateToken;
- return tokenHandler.ValidateToken(token, validationParameters, out validateToken);
- }
- }
- }
|