You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.6 KiB
48 lines
1.6 KiB
using System.Security.Claims;
|
|
using System.Security.Cryptography;
|
|
using Microsoft.IdentityModel.JsonWebTokens;
|
|
using Microsoft.IdentityModel.Tokens;
|
|
|
|
namespace OAuthServer.Services;
|
|
|
|
public class JwtService {
|
|
private readonly RSA _rsaKey;
|
|
|
|
public JwtService() {
|
|
_rsaKey = GetSigningKey();
|
|
}
|
|
|
|
public static RSA GetSigningKey() {
|
|
RSA rsaKey = RSA.Create();
|
|
const string jwtKeyPath = ".aspnet/jwt-key";
|
|
string home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
|
string fullPath = Path.Combine(home, jwtKeyPath);
|
|
if (File.Exists(fullPath)) {
|
|
rsaKey.ImportRSAPrivateKey(File.ReadAllBytes(fullPath), out _);
|
|
} else {
|
|
string? dirName = Path.GetDirectoryName(fullPath);
|
|
if (!string.IsNullOrEmpty(dirName))
|
|
Directory.CreateDirectory(dirName);
|
|
|
|
var privateKey = rsaKey.ExportRSAPrivateKey();
|
|
File.WriteAllBytes(fullPath, privateKey);
|
|
}
|
|
|
|
return rsaKey;
|
|
}
|
|
|
|
public string GenerateToken() {
|
|
var handler = new JsonWebTokenHandler();
|
|
var key = new RsaSecurityKey(_rsaKey);
|
|
var token = handler.CreateToken(new SecurityTokenDescriptor {
|
|
Subject = new ClaimsIdentity(new[] {
|
|
new Claim(JwtRegisteredClaimNames.Sub, "user1"),
|
|
new Claim("role", "External"),
|
|
new Claim("scope", "scope:1")
|
|
}),
|
|
Expires = DateTime.UtcNow.AddDays(10),
|
|
SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.RsaSha256)
|
|
});
|
|
return token;
|
|
}
|
|
} |