fix(auth): Verbesserung von isAuthenticated() durch Überprüfung des HTTP-Antwortstatus

Die isAuthenticated()-Methode wurde aktualisiert, um den Anmeldestatus anhand des HTTP-Antwortstatus zu bestimmen, anstatt sich nur auf den Antwortkörper zu verlassen. Außerdem wird sichergestellt, dass `_isLogedIn` im Fehlerfall explizit auf false gesetzt wird. Dies verbessert die Zuverlässigkeit der Sitzungsvalidierung.
This commit is contained in:
tekh 2025-07-22 15:45:38 +02:00
parent 55822047bc
commit f79fa4ca27
3 changed files with 41 additions and 50 deletions

View File

@ -36,7 +36,7 @@ export class NavMenuComponent {
isChecked = true; isChecked = true;
constructor(private dialog: MatDialog, private authService: AuthenticationService, public refreshService: RefreshService, public creationService: CreationService, public updateService: UpdateService, public transferService: TransferService, public buttonVisibilityService: ButtonVisibilityService, public deletionService: DeletionService) { constructor(private dialog: MatDialog, private authService: AuthenticationService, public refreshService: RefreshService, public creationService: CreationService, public updateService: UpdateService, public transferService: TransferService, public buttonVisibilityService: ButtonVisibilityService, public deletionService: DeletionService) {
this.authService.isAuthenticated().then().catch() this.authService.isAuthenticated()
this.updateActCount = this.updateService.totalCount; this.updateActCount = this.updateService.totalCount;
this.updateService.addChangeListener(UpdateEvent.CountChange, () => { this.updateService.addChangeListener(UpdateEvent.CountChange, () => {
this.updateActCount = updateService.totalCount; this.updateActCount = updateService.totalCount;

View File

@ -25,13 +25,14 @@ export class AuthenticationService {
async isAuthenticated(): Promise<boolean> { async isAuthenticated(): Promise<boolean> {
try { try {
const response = await firstValueFrom(this.http.get<boolean>(this.checkUrl, { withCredentials: true })); const response = await firstValueFrom(this.http.get(this.checkUrl, { withCredentials: true, observe: 'response' }));
_isLogedIn = response; _isLogedIn = response?.status === 200;
return response; return _isLogedIn;
} catch (error: any) { } catch (error: any) {
if (error?.status !== 401) if (error?.status !== 401)
this.showErrorAlert(); this.showErrorAlert();
return false; _isLogedIn = false
return _isLogedIn;
} }
} }
@ -81,4 +82,4 @@ export class AuthenticationService {
} }
let _isLogedIn: boolean = false; let _isLogedIn: boolean = false;
export const IsLogedIn = () => _isLogedIn export const IsLogedIn = () => _isLogedIn

View File

@ -1,8 +1,6 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using DigitalData.UserManager.Infrastructure.Repositories;
using DigitalData.UserManager.Application; using DigitalData.UserManager.Application;
using DigitalData.Core.Application; using DigitalData.Core.Application;
using Microsoft.AspNetCore.Authentication.Cookies;
using NLog.Web; using NLog.Web;
using NLog; using NLog;
using DigitalData.Core.API; using DigitalData.Core.API;
@ -53,13 +51,6 @@ try {
builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen();
} }
builder.Services.AddControllers(opt =>
{
opt.Conventions.Add(new RemoveIfControllerConvention()
.AndIf(c => c.ControllerName == nameof(EncryptionController).Replace("Controller", ""))
.AndIf(c => !config.GetValue<bool>("UseEncryptor")));
});
// Once the app is built, the password will be decrypted with Encryptor. lazy loading also acts as a call back method. // Once the app is built, the password will be decrypted with Encryptor. lazy loading also acts as a call back method.
Lazy<string>? cnn_str = null; Lazy<string>? cnn_str = null;
@ -94,45 +85,44 @@ try {
var authTokenKeys = config.GetSection(nameof(AuthTokenKeys)).Get<AuthTokenKeys>() ?? new(); var authTokenKeys = config.GetSection(nameof(AuthTokenKeys)).Get<AuthTokenKeys>() ?? new();
builder.Services builder.Services.AddAuthentication(options =>
.AddAuthentication(options => {
{ options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; })
}) .AddJwtBearer(opt =>
.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{ {
ValidateIssuerSigningKey = true, opt.TokenValidationParameters = new TokenValidationParameters
IssuerSigningKeyResolver = (token, securityToken, identifier, parameters) =>
{ {
var clientParams = lazyProvider.GetRequiredService<IOptions<ClientParams>>()?.Value; ValidateIssuerSigningKey = true,
var publicKey = clientParams!.PublicKeys.Get(authTokenKeys.Issuer, authTokenKeys.Audience); IssuerSigningKeyResolver = (token, securityToken, identifier, parameters) =>
return new List<SecurityKey>() { publicKey.SecurityKey };
},
ValidateIssuer = true,
ValidIssuer = authTokenKeys.Issuer,
ValidateAudience = true,
ValidAudience = authTokenKeys.Audience,
};
opt.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
// if there is no token read related cookie or query string
if (context.Token is null) // if there is no token
{ {
if (context.Request.Cookies.TryGetValue(authTokenKeys.Cookie, out var cookieToken) && cookieToken is not null) var clientParams = lazyProvider.GetRequiredService<IOptions<ClientParams>>()?.Value;
context.Token = cookieToken; var publicKey = clientParams!.PublicKeys.Get(authTokenKeys.Issuer, authTokenKeys.Audience);
else if (context.Request.Query.TryGetValue(authTokenKeys.QueryString, out var queryStrToken)) return new List<SecurityKey>() { publicKey.SecurityKey };
context.Token = queryStrToken; },
ValidateIssuer = true,
ValidIssuer = authTokenKeys.Issuer,
ValidateAudience = true,
ValidAudience = authTokenKeys.Audience,
};
opt.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
// if there is no token read related cookie or query string
if (context.Token is null) // if there is no token
{
if (context.Request.Cookies.TryGetValue(authTokenKeys.Cookie, out var cookieToken) && cookieToken is not null)
context.Token = cookieToken;
else if (context.Request.Query.TryGetValue(authTokenKeys.QueryString, out var queryStrToken))
context.Token = queryStrToken;
}
return Task.CompletedTask;
} }
return Task.CompletedTask; };
} });
};
});
builder.Services.AddSwaggerGen(setupAct => builder.Services.AddSwaggerGen(setupAct =>
{ {