Basic login an authorize in backend

This commit is contained in:
Simon Lübeß
2025-05-22 18:25:56 +02:00
parent 5c84bbc35a
commit 3e7b04df1c
7 changed files with 187 additions and 4 deletions

View File

@ -0,0 +1,7 @@
namespace USEntryCoach.Server.Data;
class LoginCredentials
{
public string Username { get; set; }
public string Password { get; set; }
}

View File

@ -0,0 +1,9 @@
namespace USEntryCoach.Server.Data;
public class User
{
public Guid Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public UserRole Role { get; set; }
}

View File

@ -0,0 +1,7 @@
namespace USEntryCoach.Server.Data;
public enum UserRole
{
Developer,
User
}

View File

@ -1,13 +1,64 @@
using System.Security.Claims;
using System.Text;
using System.Text.Json.Nodes; using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.IdentityModel.Tokens;
using USEntryCoach.Server.Data;
using USEntryCoach.Server.Services;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
// Add services to the container. // Add services to the container.
// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi(); builder.Services.AddOpenApi();
builder.Services.AddSingleton<TokenService>();
// Configure JWT token generation.
builder.Services.AddAuthentication(config =>
{
config.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
config.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(config =>
{
// TODO: Use Microsoft.Extensions.Options?
// var myOptions = new MyOptions(); // Your settings class
// builder.Configuration.GetSection("MySection").Bind(myOptions);
// myOptions now has the values
//
// TODO: This is identical in TokenService
string? secretToken = builder.Configuration.GetValue<string>("Authentication:Secret");
if (secretToken == null)
{
throw new Exception("No Authentication Secret Token set! Please define a value for \"Authentication:SecretToken\" in appsettings.json.");
}
byte[] secretKey = Encoding.ASCII.GetBytes(secretToken);
// TODO: Only for debug!
config.RequireHttpsMetadata = false;
config.SaveToken = true;
config.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(secretKey),
ValidateIssuer = false,
ValidateAudience = false
};
});
builder.Services.AddAuthorization(options =>
{
options.AddPolicy(nameof(UserRole.Developer), policy => policy.RequireRole(nameof(UserRole.Developer)));
options.AddPolicy(nameof(UserRole.User), policy => policy.RequireRole(nameof(UserRole.User)));
});
var app = builder.Build(); var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.UseDefaultFiles(); app.UseDefaultFiles();
app.MapStaticAssets(); app.MapStaticAssets();
@ -24,13 +75,61 @@ string? apiKey = app.Configuration.GetValue<string>("API:OpenAI");
client.DefaultRequestHeaders.Clear(); client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}");
app.MapPost("/login", Login);
app.MapGet("/hello", () => "Hello World!").RequireAuthorization("admin_greetings");
async Task<IResult> Login(LoginCredentials credentials, TokenService tokenService, HttpContext context)
{
// TODO: Check with database
User? user = null;
if (credentials is {Username:"developer", Password:"dev"})
{
user = new User()
{
Username = credentials.Username,
Password = credentials.Password,
Id = Guid.CreateVersion7(),
Role = UserRole.Developer
};
}
else if (credentials is {Username:"user", Password:"us"})
{
user = new User()
{
Username = credentials.Username,
Password = credentials.Password,
Id = Guid.CreateVersion7(),
Role = UserRole.User
};
}
if (user == null)
{
return Results.Unauthorized();
}
var token = tokenService.GenerateToken(user);
return Results.Ok(new { user = user, token = token });
}
app.MapGet("/developer", (ClaimsPrincipal user) =>
{
Results.Ok(new { message = $"Authenticated as { user?.Identity?.Name }" });
}).RequireAuthorization(nameof(UserRole.Developer));
app.MapGet("/user", (ClaimsPrincipal user) =>
{
Results.Ok(new { message = $"Authenticated as { user?.Identity?.Name }" });
}).RequireAuthorization(nameof(UserRole.User));
app.MapGet("/ephemeral_token", async () => app.MapGet("/ephemeral_token", async () =>
{ {
if (apiKey == null) if (apiKey == null)
throw new Exception("API key not set"); throw new Exception("API key not set");
#pragma warning disable OPENAI002
var options = new var options = new
{ {
model = "gpt-4o-mini-realtime-preview", model = "gpt-4o-mini-realtime-preview",
@ -44,8 +143,6 @@ app.MapGet("/ephemeral_token", async () =>
//}//ConversationTurnDetectionOptions.CreateServerVoiceActivityTurnDetectionOptions(0.5f, TimeSpan.FromMilliseconds(300), TimeSpan.FromMilliseconds(500), true) //}//ConversationTurnDetectionOptions.CreateServerVoiceActivityTurnDetectionOptions(0.5f, TimeSpan.FromMilliseconds(300), TimeSpan.FromMilliseconds(500), true)
}; };
#pragma warning restore OPENAI002
try try
{ {
JsonContent content = JsonContent.Create(options); JsonContent content = JsonContent.Create(options);

View File

@ -0,0 +1,56 @@
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;
using USEntryCoach.Server.Data;
namespace USEntryCoach.Server.Services;
public class TokenService
{
private byte[] _secretToken;
private double _jwtExpiryMinutes;
private const double DefaultJwtExpiryMinutes = 15;
public TokenService(IConfiguration configuration)
{
string? secretToken = configuration.GetValue<string>("Authentication:Secret");
if (secretToken == null)
{
throw new Exception("No Authentication Secret Token set! Please define a value for \"Authentication:SecretToken\" in appsettings.json.");
}
_secretToken = Encoding.ASCII.GetBytes(secretToken);
double? jwtExpiryMinutes = configuration.GetValue<double?>("Authentication:JwtExpiryMinutes");
if (jwtExpiryMinutes == null)
{
// TODO: Use logger
Console.WriteLine($"Warning: No expiry time for jwt session tokens defined. Using {DefaultJwtExpiryMinutes} minutes.");
}
_jwtExpiryMinutes = jwtExpiryMinutes ?? DefaultJwtExpiryMinutes;
}
public string GenerateToken(User user)
{
JwtSecurityTokenHandler tokenHandler = new();
SecurityTokenDescriptor tokenDescriptor = new()
{
Subject = new ClaimsIdentity([
new Claim(ClaimTypes.Name, user.Username),
//new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Role, user.Role.ToString())
]),
Expires = DateTime.UtcNow.AddMinutes(_jwtExpiryMinutes),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(_secretToken), SecurityAlgorithms.HmacSha256Signature)
};
SecurityToken token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}

View File

@ -13,6 +13,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="9.0.5" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.4" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="9.0.4" />
<PackageReference Include="Microsoft.AspNetCore.SpaProxy"> <PackageReference Include="Microsoft.AspNetCore.SpaProxy">
<Version>9.*-*</Version> <Version>9.*-*</Version>

View File

@ -4,5 +4,11 @@
"Default": "Information", "Default": "Information",
"Microsoft.AspNetCore": "Warning" "Microsoft.AspNetCore": "Warning"
} }
},
"API": {
"OpenAI": "Please set the key in secrets.json! NEVER HERE!!!"
},
"Authentication": {
"Secret": "Please provide a GUID (without dashes) as secret."
} }
} }