mirror of
https://bitbucket.org/myhomie/mycorerepository.git
synced 2025-12-06 17:51:20 +00:00
58 lines
1.8 KiB
C#
58 lines
1.8 KiB
C#
using Microsoft.IdentityModel.Tokens;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IdentityModel.Tokens.Jwt;
|
|
using System.Linq;
|
|
using System.Security.Claims;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace MyCore.Services
|
|
{
|
|
public class TokenService
|
|
{
|
|
public object GenerateToken(string username)
|
|
{
|
|
var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("%G2YZ=\tgN7fC9M$FXDt#q*a&]Z")); // Put the secret in a file or something
|
|
|
|
var claims = new Claim[] {
|
|
new Claim(ClaimTypes.Name, username),
|
|
new Claim(JwtRegisteredClaimNames.Email, "john.doe@blinkingcaret.com"),
|
|
new Claim(ClaimTypes.Role, "Admin")
|
|
};
|
|
|
|
var token = new JwtSecurityToken(
|
|
issuer: "MyCore App",
|
|
audience: "Miotecher",
|
|
claims: claims,
|
|
notBefore: DateTime.Now,
|
|
expires: DateTime.Now.AddDays(28),
|
|
signingCredentials: new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256)
|
|
);
|
|
|
|
string jwtToken = new JwtSecurityTokenHandler().WriteToken(token);
|
|
|
|
return jwtToken;
|
|
}
|
|
|
|
public static string GenerateSHA256String(string inputString)
|
|
{
|
|
SHA256 sha256 = SHA256Managed.Create();
|
|
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
|
|
byte[] hash = sha256.ComputeHash(bytes);
|
|
return GetStringFromHash(hash);
|
|
}
|
|
|
|
public static string GetStringFromHash(byte[] hash)
|
|
{
|
|
StringBuilder result = new StringBuilder();
|
|
for (int i = 0; i < hash.Length; i++)
|
|
{
|
|
result.Append(hash[i].ToString("X2"));
|
|
}
|
|
return result.ToString();
|
|
}
|
|
}
|
|
}
|