Add token authentication.

This commit is contained in:
2025-11-13 14:36:14 +00:00
parent be83594ea9
commit 6962be93a4
4 changed files with 116 additions and 21 deletions

View File

@@ -30,5 +30,8 @@
<PackageVersion Include="Packaging.Targets" Version="0.1.189"/>
<!-- Unique to Marechai.Server.csproj -->
<PackageVersion Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0"/>
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.11"/>
<PackageVersion Include="Microsoft.AspNetCore.Components.Authorization" Version="9.0.11"/>
<PackageVersion Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="9.0.11"/>
</ItemGroup>
</Project>

View File

@@ -9,6 +9,8 @@
<PackageReference Include="Markdig"/>
<PackageReference Include="Microsoft.AspNetCore.OpenApi"/>
<PackageReference Include="Svg.Skia"/>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer"/>
<PackageReference Include="Microsoft.AspNetCore.Identity.UI"/>
</ItemGroup>
<ItemGroup>

View File

@@ -6,12 +6,15 @@ using Marechai.Database;
using Marechai.Database.Models;
using Marechai.Helpers;
using Marechai.Server.Helpers;
using Marechai.Server.Services;
using Markdig;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Version = Marechai.Server.Interop.Version;
namespace Marechai.Server;
@@ -156,6 +159,32 @@ file class Program
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ClockSkew = TimeSpan.Zero,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = false,
ValidateIssuerSigningKey = true,
ValidIssuer = "apiWithAuthBackend",
ValidAudience = "apiWithAuthBackend",
IssuerSigningKey =
new
SymmetricSecurityKey("!SomethingSecret!!SomethingSecret!!SomethingSecret!!SomethingSecret!"u8
.ToArray())
};
});
builder.Services.AddDbContextFactory<MarechaiContext>(options => options.UseLazyLoadingProxies()
.UseMySql(builder.Configuration
.GetConnectionString("DefaultConnection"),
@@ -164,6 +193,12 @@ file class Program
Version(10, 5, 0)),
b => b.UseMicrosoftJson()));
builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<ApplicationRole>()
.AddEntityFrameworkStores<MarechaiContext>();
builder.Services.AddScoped<TokenService, TokenService>();
WebApplication app = builder.Build();
// Configure the HTTP request pipeline.
@@ -171,6 +206,7 @@ file class Program
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

View File

@@ -0,0 +1,54 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
using Microsoft.IdentityModel.Tokens;
namespace Marechai.Server.Services;
public sealed class TokenService
{
public string CreateToken(IdentityUser user, IList<string> roles)
{
JwtSecurityToken token = CreateJwtToken(CreateClaims(user, roles), CreateSigningCredentials());
var tokenHandler = new JwtSecurityTokenHandler();
return tokenHandler.WriteToken(token);
}
JwtSecurityToken CreateJwtToken(List<Claim> claims, SigningCredentials credentials) =>
new("apiWithAuthBackend", "apiWithAuthBackend", claims, expires: null, signingCredentials: credentials);
List<Claim> CreateClaims(IdentityUser user, IList<string> roles)
{
try
{
List<Claim> claims =
[
new(JwtRegisteredClaimNames.Sub, "TokenForTheApiWithAuth"),
new(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new(JwtRegisteredClaimNames.Iat,
EpochTime.GetIntDate(DateTime.UtcNow).ToString(CultureInfo.InvariantCulture)),
new(ClaimTypes.Sid, user.Id), new(ClaimTypes.Name, user.UserName), new(ClaimTypes.Email, user.Email)
];
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
return claims;
}
catch(Exception e)
{
Console.WriteLine(e);
throw;
}
}
SigningCredentials CreateSigningCredentials() =>
new(new SymmetricSecurityKey("!SomethingSecret!!SomethingSecret!!SomethingSecret!!SomethingSecret!"u8
.ToArray()),
SecurityAlgorithms.HmacSha256);
}