From f79fa4ca27cb853302ef8ded6a8fe6c3ef4fe397 Mon Sep 17 00:00:00 2001 From: TekH Date: Tue, 22 Jul 2025 15:45:38 +0200 Subject: [PATCH] =?UTF-8?q?fix(auth):=20Verbesserung=20von=20isAuthenticat?= =?UTF-8?q?ed()=20durch=20=C3=9Cberpr=C3=BCfung=20des=20HTTP-Antwortstatus?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .../components/nav-menu/nav-menu.component.ts | 2 +- .../services/api/authentication.service.ts | 11 +-- DigitalData.UserManager.API/Program.cs | 76 ++++++++----------- 3 files changed, 40 insertions(+), 49 deletions(-) diff --git a/DigitalData.UserManager.API/ClientApp/user_manager_ui/src/app/components/nav-menu/nav-menu.component.ts b/DigitalData.UserManager.API/ClientApp/user_manager_ui/src/app/components/nav-menu/nav-menu.component.ts index 0223e4e..520c6ad 100644 --- a/DigitalData.UserManager.API/ClientApp/user_manager_ui/src/app/components/nav-menu/nav-menu.component.ts +++ b/DigitalData.UserManager.API/ClientApp/user_manager_ui/src/app/components/nav-menu/nav-menu.component.ts @@ -36,7 +36,7 @@ export class NavMenuComponent { 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) { - this.authService.isAuthenticated().then().catch() + this.authService.isAuthenticated() this.updateActCount = this.updateService.totalCount; this.updateService.addChangeListener(UpdateEvent.CountChange, () => { this.updateActCount = updateService.totalCount; diff --git a/DigitalData.UserManager.API/ClientApp/user_manager_ui/src/app/services/api/authentication.service.ts b/DigitalData.UserManager.API/ClientApp/user_manager_ui/src/app/services/api/authentication.service.ts index af135a6..fb17c0c 100644 --- a/DigitalData.UserManager.API/ClientApp/user_manager_ui/src/app/services/api/authentication.service.ts +++ b/DigitalData.UserManager.API/ClientApp/user_manager_ui/src/app/services/api/authentication.service.ts @@ -25,13 +25,14 @@ export class AuthenticationService { async isAuthenticated(): Promise { try { - const response = await firstValueFrom(this.http.get(this.checkUrl, { withCredentials: true })); - _isLogedIn = response; - return response; + const response = await firstValueFrom(this.http.get(this.checkUrl, { withCredentials: true, observe: 'response' })); + _isLogedIn = response?.status === 200; + return _isLogedIn; } catch (error: any) { if (error?.status !== 401) this.showErrorAlert(); - return false; + _isLogedIn = false + return _isLogedIn; } } @@ -81,4 +82,4 @@ export class AuthenticationService { } let _isLogedIn: boolean = false; -export const IsLogedIn = () => _isLogedIn \ No newline at end of file +export const IsLogedIn = () => _isLogedIn diff --git a/DigitalData.UserManager.API/Program.cs b/DigitalData.UserManager.API/Program.cs index c3d8bc9..b964af9 100644 --- a/DigitalData.UserManager.API/Program.cs +++ b/DigitalData.UserManager.API/Program.cs @@ -1,8 +1,6 @@ using Microsoft.EntityFrameworkCore; -using DigitalData.UserManager.Infrastructure.Repositories; using DigitalData.UserManager.Application; using DigitalData.Core.Application; -using Microsoft.AspNetCore.Authentication.Cookies; using NLog.Web; using NLog; using DigitalData.Core.API; @@ -53,13 +51,6 @@ try { builder.Services.AddSwaggerGen(); } - builder.Services.AddControllers(opt => - { - opt.Conventions.Add(new RemoveIfControllerConvention() - .AndIf(c => c.ControllerName == nameof(EncryptionController).Replace("Controller", "")) - .AndIf(c => !config.GetValue("UseEncryptor"))); - }); - // Once the app is built, the password will be decrypted with Encryptor. lazy loading also acts as a call back method. Lazy? cnn_str = null; @@ -94,45 +85,44 @@ try { var authTokenKeys = config.GetSection(nameof(AuthTokenKeys)).Get() ?? new(); - builder.Services - .AddAuthentication(options => - { - options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; - }) - .AddJwtBearer(opt => - { - opt.TokenValidationParameters = new TokenValidationParameters + builder.Services.AddAuthentication(options => + { + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; + }) + .AddJwtBearer(opt => { - ValidateIssuerSigningKey = true, - IssuerSigningKeyResolver = (token, securityToken, identifier, parameters) => + opt.TokenValidationParameters = new TokenValidationParameters { - var clientParams = lazyProvider.GetRequiredService>()?.Value; - var publicKey = clientParams!.PublicKeys.Get(authTokenKeys.Issuer, authTokenKeys.Audience); - return new List() { publicKey.SecurityKey }; - }, - ValidateIssuer = true, - ValidIssuer = authTokenKeys.Issuer, - ValidateAudience = true, - ValidAudience = authTokenKeys.Audience, - }; - - opt.Events = new JwtBearerEvents - { - OnMessageReceived = context => + ValidateIssuerSigningKey = true, + IssuerSigningKeyResolver = (token, securityToken, identifier, parameters) => + { + var clientParams = lazyProvider.GetRequiredService>()?.Value; + var publicKey = clientParams!.PublicKeys.Get(authTokenKeys.Issuer, authTokenKeys.Audience); + return new List() { publicKey.SecurityKey }; + }, + ValidateIssuer = true, + ValidIssuer = authTokenKeys.Issuer, + ValidateAudience = true, + ValidAudience = authTokenKeys.Audience, + }; + + opt.Events = new JwtBearerEvents { - // if there is no token read related cookie or query string - if (context.Token is null) // if there is no token + OnMessageReceived = context => { - 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; + // 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 => {