Generating tokens

master
D4VID 2 years ago
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());
}
}

@ -7,6 +7,7 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using OAuthServer;
using OAuthServer.Services;
var builder = WebApplication.CreateBuilder(args);
@ -55,23 +56,7 @@ builder.Services.AddIdentity<IdentityUser, IdentityRole>(options => { options.St
.AddDefaultTokenProviders();
// Load the signing key from a file if it exists or create a new one
var 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);
}
var rsaKey = JwtService.GetSigningKey();
// Add the JWT authentication method
builder.Services.AddAuthentication().AddJwtBearer("OAuthToken", options =>
@ -151,6 +136,8 @@ builder.Services.AddAuthorization(options =>
);
});
builder.Services.AddSingleton<JwtService>();
var app = builder.Build();
// Configure the HTTP request pipeline.

@ -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…
Cancel
Save