parent
f2054dd368
commit
152c7b148c
@ -0,0 +1,24 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using OAuthServer.Services;
|
||||
|
||||
namespace OAuthServer.Controllers;
|
||||
|
||||
[ApiController]
|
||||
public class OAuthController : ControllerBase
|
||||
{
|
||||
private readonly ILogger<OAuthController> _logger;
|
||||
private readonly JwtService _jwt;
|
||||
|
||||
public OAuthController(ILogger<OAuthController> logger, JwtService jwt)
|
||||
{
|
||||
_logger = logger;
|
||||
_jwt = jwt;
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Route("get-token")]
|
||||
public ActionResult GenerateToken()
|
||||
{
|
||||
return Ok(_jwt.GenerateToken());
|
||||
}
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
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;
|
||||
}
|
||||
}
|
Loading…
Reference in new issue