From 54c4cb316059c44ed8b0e73f7a723581536ae571 Mon Sep 17 00:00:00 2001 From: antoineatstariongroup Date: Tue, 21 Jan 2025 13:13:44 +0100 Subject: [PATCH] Unit tests for Handler --- ...onymousAuthenticationHandlerTestFixture.cs | 88 ++++++ .../BasicAuthenticationHandlerTestFixture.cs | 275 ++++++++++++++++++ ...tBearerAuthenticationHandlerTestFixture.cs | 232 +++++++++++++++ .../Bearer/JwtBearerAuthenticationHandler.cs | 4 +- 4 files changed, 596 insertions(+), 3 deletions(-) create mode 100644 CometServer.Tests/Authentication/Anonymous/AnonymousAuthenticationHandlerTestFixture.cs create mode 100644 CometServer.Tests/Authentication/Basic/BasicAuthenticationHandlerTestFixture.cs create mode 100644 CometServer.Tests/Authentication/Bearer/JwtBearerAuthenticationHandlerTestFixture.cs diff --git a/CometServer.Tests/Authentication/Anonymous/AnonymousAuthenticationHandlerTestFixture.cs b/CometServer.Tests/Authentication/Anonymous/AnonymousAuthenticationHandlerTestFixture.cs new file mode 100644 index 00000000..c56f79f9 --- /dev/null +++ b/CometServer.Tests/Authentication/Anonymous/AnonymousAuthenticationHandlerTestFixture.cs @@ -0,0 +1,88 @@ +// -------------------------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2015-2025 Starion Group S.A. +// +// Author: Sam Gerené, Alex Vorobiev, Alexander van Delft, Nathanael Smiechowski, Antoine Théate +// +// This file is part of CDP4-COMET Webservices Community Edition. +// The CDP4-COMET Web Services Community Edition is the Starion implementation of ECSS-E-TM-10-25 Annex A and Annex C. +// +// The CDP4-COMET Web Services Community Edition is free software; you can redistribute it and/or +// modify it under the terms of the GNU Affero General Public +// License as published by the Free Software Foundation; either +// version 3 of the License, or (at your option) any later version. +// +// The CDP4-COMET Web Services Community Edition is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . +// +// -------------------------------------------------------------------------------------------------------------------- + +namespace CometServer.Tests.Authentication.Anonymous +{ + using System.Linq; + using System.Security.Claims; + using System.Text.Encodings.Web; + using System.Threading.Tasks; + + using CometServer.Authentication.Anonymous; + + using Microsoft.AspNetCore.Authentication; + using Microsoft.AspNetCore.Http; + using Microsoft.Extensions.Logging; + using Microsoft.Extensions.Options; + + using Moq; + + using NUnit.Framework; + + [TestFixture] + public class AnonymousAuthenticationHandlerTestFixture + { + public AnonymousAuthenticationHandler handler; + public Mock> optionsMonitor; + public Mock loggerFactory; + public Mock encoder; + public Mock systemClock; + + [SetUp] + public void Setup() + { + this.optionsMonitor = new Mock>(); + + this.optionsMonitor + .Setup(x => x.Get(It.IsAny())) + .Returns(new AnonymousAuthenticationOptions()); + + this.loggerFactory = new Mock(); + var logger = new Mock>(); + this.loggerFactory.Setup(x => x.CreateLogger(It.IsAny())).Returns(logger.Object); + + this.encoder = new Mock(); + this.systemClock = new Mock(); + this.handler = new AnonymousAuthenticationHandler(this.optionsMonitor.Object, this.loggerFactory.Object, this.encoder.Object, this.systemClock.Object); + } + + [Test] + public async Task VerifyHandleAnonymousAuthentication() + { + var context = new DefaultHttpContext(); + + await this.handler.InitializeAsync(new AuthenticationScheme(AnonymousAuthenticationDefaults.AuthenticationScheme, AnonymousAuthenticationDefaults.DisplayName, + typeof(AnonymousAuthenticationHandler)), context); + + var result = await this.handler.AuthenticateAsync(); + + Assert.Multiple(() => + { + Assert.That(result.Succeeded, Is.True); + Assert.That(result.Principal, Is.Not.Null); + Assert.That(result.Principal.Claims.Single(x => x.Type == ClaimTypes.Name).Value, Is.EqualTo("anonymous")); + }); + } + } +} diff --git a/CometServer.Tests/Authentication/Basic/BasicAuthenticationHandlerTestFixture.cs b/CometServer.Tests/Authentication/Basic/BasicAuthenticationHandlerTestFixture.cs new file mode 100644 index 00000000..886e1280 --- /dev/null +++ b/CometServer.Tests/Authentication/Basic/BasicAuthenticationHandlerTestFixture.cs @@ -0,0 +1,275 @@ +// -------------------------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2015-2025 Starion Group S.A. +// +// Author: Sam Gerené, Alex Vorobiev, Alexander van Delft, Nathanael Smiechowski, Antoine Théate +// +// This file is part of CDP4-COMET Webservices Community Edition. +// The CDP4-COMET Web Services Community Edition is the Starion implementation of ECSS-E-TM-10-25 Annex A and Annex C. +// +// The CDP4-COMET Web Services Community Edition is free software; you can redistribute it and/or +// modify it under the terms of the GNU Affero General Public +// License as published by the Free Software Foundation; either +// version 3 of the License, or (at your option) any later version. +// +// The CDP4-COMET Web Services Community Edition is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . +// +// -------------------------------------------------------------------------------------------------------------------- + +namespace CometServer.Tests.Authentication.Basic +{ + using System; + using System.Collections.Generic; + using System.Text.Encodings.Web; + using System.Threading.Tasks; + + using Carter; + + using CDP4Authentication; + + using CometServer.Authentication; + using CometServer.Authentication.Anonymous; + using CometServer.Authentication.Basic; + using CometServer.Configuration; + using CometServer.Health; + + using Microsoft.AspNetCore.Authentication; + using Microsoft.AspNetCore.Http; + using Microsoft.Extensions.Logging; + using Microsoft.Extensions.Options; + using Microsoft.Extensions.Primitives; + using Microsoft.Net.Http.Headers; + + using Moq; + + using NUnit.Framework; + + [TestFixture] + public class BasicAuthenticationHandlerTestFixture + { + private BasicAuthenticationHandler handler; + private Mock> optionsMonitor; + private Mock loggerFactory; + private Mock encoder; + private Mock systemClock; + private Mock authenticatonPersonAuthenticator; + private Mock cometHasStartedService; + private Mock appConfigService; + private Mock jsonResponseNegotiator; + private Mock requestService; + private Mock authenticationService; + + [SetUp] + public void Setup() + { + this.optionsMonitor = new Mock>(); + + this.optionsMonitor + .Setup(x => x.Get(It.IsAny())) + .Returns(new BasicAuthenticationOptions()); + + this.loggerFactory = new Mock(); + var logger = new Mock>(); + this.loggerFactory.Setup(x => x.CreateLogger(It.IsAny())).Returns(logger.Object); + + this.encoder = new Mock(); + this.systemClock = new Mock(); + this.authenticatonPersonAuthenticator = new Mock(); + this.cometHasStartedService = new Mock(); + this.appConfigService = new Mock(); + this.jsonResponseNegotiator = new Mock(); + this.jsonResponseNegotiator.Setup(x => x.CanHandle(new MediaTypeHeaderValue("application/json"))).Returns(true); + this.requestService = new Mock(); + this.requestService.Setup(x => x.GetService(typeof(IEnumerable))).Returns(new List{this.jsonResponseNegotiator.Object}); + this.authenticationService = new Mock(); + + this.requestService.Setup(x => x.GetService(typeof(IAuthenticationService))).Returns(this.authenticationService.Object); + + this.handler = new BasicAuthenticationHandler(this.optionsMonitor.Object, this.loggerFactory.Object, this.encoder.Object, this.systemClock.Object, + this.authenticatonPersonAuthenticator.Object, this.cometHasStartedService.Object,this.appConfigService.Object); + } + + [Test] + public async Task VerifyAuthenticationFailsWhenNotStarted() + { + var context = new DefaultHttpContext + { + RequestServices = this.requestService.Object + }; + + context.Request.Headers.Authorization = new StringValues("Basic"); + + this.cometHasStartedService.Setup(x => x.GetHasStartedAndIsReady()).Returns(new ServerStatus(false, DateTime.Now)); + + await this.handler.InitializeAsync(new AuthenticationScheme(BasicAuthenticationDefaults.AuthenticationScheme, BasicAuthenticationDefaults.DisplayName, typeof(BasicAuthenticationHandler)), context); + var result = await this.handler.AuthenticateAsync(); + + Assert.That(result.Succeeded, Is.False); + + await this.handler.ChallengeAsync(result.Properties); + + Assert.That(context.Response.StatusCode, Is.EqualTo(503)); + } + + [Test] + public async Task VerifyAuthenticationFailsBasedOnConfig() + { + var context = new DefaultHttpContext + { + RequestServices = this.requestService.Object + }; + + context.Request.Headers.Authorization = new StringValues("Basic"); + + this.cometHasStartedService.Setup(x => x.GetHasStartedAndIsReady()).Returns(new ServerStatus(true, DateTime.Now)); + await this.handler.InitializeAsync(new AuthenticationScheme(BasicAuthenticationDefaults.AuthenticationScheme, BasicAuthenticationDefaults.DisplayName, typeof(BasicAuthenticationHandler)), context); + + this.appConfigService.Setup(x => x.IsAuthenticationSchemeEnabled(this.handler.Scheme.Name)).Returns(false); + + var result = await this.handler.AuthenticateAsync(); + + Assert.That(result.Succeeded, Is.False); + + await this.handler.ChallengeAsync(result.Properties); + + Assert.That(context.Response.StatusCode, Is.EqualTo(403)); + } + + [Test] + public async Task VerifyAuthenticationNotSucceedNorFailedWithEmptyHeader() + { + var context = new DefaultHttpContext + { + RequestServices = this.requestService.Object + }; + + this.cometHasStartedService.Setup(x => x.GetHasStartedAndIsReady()).Returns(new ServerStatus(true, DateTime.Now)); + await this.handler.InitializeAsync(new AuthenticationScheme(BasicAuthenticationDefaults.AuthenticationScheme, BasicAuthenticationDefaults.DisplayName, typeof(BasicAuthenticationHandler)), context); + + this.appConfigService.Setup(x => x.IsAuthenticationSchemeEnabled(this.handler.Scheme.Name)).Returns(true); + var result = await this.handler.AuthenticateAsync(); + + Assert.That(result.Succeeded, Is.False); + + await this.handler.ChallengeAsync(result.Properties); + + Assert.That(context.Response.StatusCode, Is.EqualTo(200)); + } + + [Test] + public async Task VerifyAuthenticationNotSucceedNorFailedWithInvalidHeader() + { + var context = new DefaultHttpContext + { + RequestServices = this.requestService.Object + }; + + context.Request.Headers.Authorization = new StringValues("Invalid"); + + this.cometHasStartedService.Setup(x => x.GetHasStartedAndIsReady()).Returns(new ServerStatus(true, DateTime.Now)); + await this.handler.InitializeAsync(new AuthenticationScheme(BasicAuthenticationDefaults.AuthenticationScheme, BasicAuthenticationDefaults.DisplayName, typeof(BasicAuthenticationHandler)), context); + + this.appConfigService.Setup(x => x.IsAuthenticationSchemeEnabled(this.handler.Scheme.Name)).Returns(true); + var result = await this.handler.AuthenticateAsync(); + + Assert.That(result.Succeeded, Is.False); + + await this.handler.ChallengeAsync(result.Properties); + + Assert.That(context.Response.StatusCode, Is.EqualTo(200)); + } + + [Test] + public async Task VerifyAuthenticationFailsWithInvalidCredentialsFormat() + { + var context = new DefaultHttpContext + { + RequestServices = this.requestService.Object + }; + + const string credentials = "user"; + + context.Request.Headers.Authorization = new StringValues($"Basic {Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(credentials))}"); + + this.cometHasStartedService.Setup(x => x.GetHasStartedAndIsReady()).Returns(new ServerStatus(true, DateTime.Now)); + await this.handler.InitializeAsync(new AuthenticationScheme(BasicAuthenticationDefaults.AuthenticationScheme, BasicAuthenticationDefaults.DisplayName, typeof(BasicAuthenticationHandler)), context); + + this.appConfigService.Setup(x => x.IsAuthenticationSchemeEnabled(this.handler.Scheme.Name)).Returns(true); + var result = await this.handler.AuthenticateAsync(); + + Assert.Multiple(() => + { + Assert.That(result.Failure, Is.Not.Null); + Assert.That(result.Failure.Message, Is.EqualTo("Invalid Basic authentication header format.")); + }); + + await this.handler.ChallengeAsync(result.Properties); + + Assert.That(context.Response.StatusCode, Is.EqualTo(401)); + } + + [Test] + public async Task VerifyAuthenticationFailsdWithInvalidCredential() + { + var context = new DefaultHttpContext + { + RequestServices = this.requestService.Object + }; + + const string username ="user"; + const string password = "password"; + + context.Request.Headers.Authorization = new StringValues($"Basic {Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{username}:{password}"))}"); + + this.cometHasStartedService.Setup(x => x.GetHasStartedAndIsReady()).Returns(new ServerStatus(true, DateTime.Now)); + await this.handler.InitializeAsync(new AuthenticationScheme(BasicAuthenticationDefaults.AuthenticationScheme, BasicAuthenticationDefaults.DisplayName, typeof(BasicAuthenticationHandler)), context); + + this.appConfigService.Setup(x => x.IsAuthenticationSchemeEnabled(this.handler.Scheme.Name)).Returns(true); + this.authenticatonPersonAuthenticator.Setup(x => x.Authenticate(username, password)).ReturnsAsync((AuthenticationPerson)null); + var result = await this.handler.AuthenticateAsync(); + + Assert.Multiple(() => + { + Assert.That(result.Failure, Is.Not.Null); + Assert.That(result.Failure.Message, Is.EqualTo("Invalid username or password.")); + }); + + await this.handler.ChallengeAsync(result.Properties); + + Assert.That(context.Response.StatusCode, Is.EqualTo(401)); + } + + [Test] + public async Task VerifyAuthenticationSuccessWithValidCredentials() + { + var context = new DefaultHttpContext + { + RequestServices = this.requestService.Object + }; + + const string username ="user"; + const string password = "password"; + + context.Request.Headers.Authorization = new StringValues($"Basic {Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes($"{username}:{password}"))}"); + + this.cometHasStartedService.Setup(x => x.GetHasStartedAndIsReady()).Returns(new ServerStatus(true, DateTime.Now)); + await this.handler.InitializeAsync(new AuthenticationScheme(BasicAuthenticationDefaults.AuthenticationScheme, BasicAuthenticationDefaults.DisplayName, typeof(BasicAuthenticationHandler)), context); + + this.appConfigService.Setup(x => x.IsAuthenticationSchemeEnabled(this.handler.Scheme.Name)).Returns(true); + this.authenticatonPersonAuthenticator.Setup(x => x.Authenticate(username, password)).ReturnsAsync(new AuthenticationPerson(Guid.NewGuid(), 1)); + var result = await this.handler.AuthenticateAsync(); + + Assert.Multiple(() => + { + Assert.That(result.Succeeded, Is.True); + Assert.That(result.Principal!.Identity!.Name, Is.EqualTo(username)); + }); + } + } +} diff --git a/CometServer.Tests/Authentication/Bearer/JwtBearerAuthenticationHandlerTestFixture.cs b/CometServer.Tests/Authentication/Bearer/JwtBearerAuthenticationHandlerTestFixture.cs new file mode 100644 index 00000000..e9d68d4a --- /dev/null +++ b/CometServer.Tests/Authentication/Bearer/JwtBearerAuthenticationHandlerTestFixture.cs @@ -0,0 +1,232 @@ +// -------------------------------------------------------------------------------------------------------------------- +// +// Copyright (c) 2015-2025 Starion Group S.A. +// +// Author: Sam Gerené, Alex Vorobiev, Alexander van Delft, Nathanael Smiechowski, Antoine Théate +// +// This file is part of CDP4-COMET Webservices Community Edition. +// The CDP4-COMET Web Services Community Edition is the Starion implementation of ECSS-E-TM-10-25 Annex A and Annex C. +// +// The CDP4-COMET Web Services Community Edition is free software; you can redistribute it and/or +// modify it under the terms of the GNU Affero General Public +// License as published by the Free Software Foundation; either +// version 3 of the License, or (at your option) any later version. +// +// The CDP4-COMET Web Services Community Edition is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . +// +// -------------------------------------------------------------------------------------------------------------------- + +namespace CometServer.Tests.Authentication.Bearer +{ + using System; + using System.Collections.Generic; + using System.Text; + using System.Text.Encodings.Web; + using System.Threading.Tasks; + + using Carter; + + using CDP4Authentication; + + using CometServer.Authentication; + using CometServer.Authentication.Basic; + using CometServer.Authentication.Bearer; + using CometServer.Configuration; + using CometServer.Health; + + using Microsoft.AspNetCore.Authentication; + using Microsoft.AspNetCore.Authentication.JwtBearer; + using Microsoft.AspNetCore.Http; + using Microsoft.Extensions.Logging; + using Microsoft.Extensions.Logging.Abstractions; + using Microsoft.Extensions.Options; + using Microsoft.Extensions.Primitives; + using Microsoft.IdentityModel.Tokens; + using Microsoft.Net.Http.Headers; + + using Moq; + + using NUnit.Framework; + + using JwtBearerDefaults = CometServer.Authentication.Bearer.JwtBearerDefaults; + + [TestFixture] + public class JwtBearerAuthenticationHandlerTestFixture + { + private JwtBearerAuthenticationHandler handler; + private Mock> optionsMonitor; + private Mock loggerFactory; + private Mock encoder; + private Mock systemClock; + private Mock cometHasStartedService; + private Mock appConfigService; + private Mock jsonResponseNegotiator; + private Mock requestService; + private JwtTokenService jwtTokenService; + private const string key = "68D58F267F5FFEC6B63A5907B3D96B80F101DA5AE167418FCFF416EB123C896B"; + + [SetUp] + public void Setup() + { + var appConfig = new AppConfig(); + appConfig.AuthenticationConfig.LocalJwtAuthenticationConfig.SymmetricSecurityKey = key; + + this.optionsMonitor = new Mock>(); + + this.optionsMonitor + .Setup(x => x.Get(It.IsAny())) + .Returns(new JwtBearerOptions() + { + TokenValidationParameters = + { + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(key)), + ValidateIssuer = true, + ValidIssuer = appConfig.AuthenticationConfig.LocalJwtAuthenticationConfig.ValidIssuer, + ValidateAudience = true, + ValidAudience = appConfig.AuthenticationConfig.LocalJwtAuthenticationConfig.ValidAudience + } + }); + + this.loggerFactory = new Mock(); + var logger = new Mock>(); + this.loggerFactory.Setup(x => x.CreateLogger(It.IsAny())).Returns(logger.Object); + + this.encoder = new Mock(); + this.systemClock = new Mock(); + this.cometHasStartedService = new Mock(); + this.appConfigService = new Mock(); + this.jsonResponseNegotiator = new Mock(); + this.jsonResponseNegotiator.Setup(x => x.CanHandle(new MediaTypeHeaderValue("application/json"))).Returns(true); + this.requestService = new Mock(); + this.requestService.Setup(x => x.GetService(typeof(IEnumerable))).Returns(new List{this.jsonResponseNegotiator.Object}); + + this.handler = new JwtBearerAuthenticationHandler(this.optionsMonitor.Object, this.loggerFactory.Object, this.encoder.Object, this.systemClock.Object, + this.cometHasStartedService.Object,this.appConfigService.Object); + + this.appConfigService.Setup( x=> x.AppConfig).Returns(appConfig); + this.jwtTokenService = new JwtTokenService(new NullLogger(), this.appConfigService.Object); + } + + [Test] + public async Task VerifyAuthenticationFailsWhenNotStarted() + { + var context = new DefaultHttpContext + { + RequestServices = this.requestService.Object + }; + + context.Request.Headers.Authorization = new StringValues(JwtBearerDefaults.LocalAuthenticationScheme); + + this.cometHasStartedService.Setup(x => x.GetHasStartedAndIsReady()).Returns(new ServerStatus(false, DateTime.Now)); + + await this.handler.InitializeAsync(new AuthenticationScheme(JwtBearerDefaults.LocalAuthenticationScheme, "", typeof(JwtBearerAuthenticationHandler)), context); + var result = await this.handler.AuthenticateAsync(); + + Assert.That(result.Succeeded, Is.False); + + await this.handler.ChallengeAsync(result.Properties); + + Assert.That(context.Response.StatusCode, Is.EqualTo(503)); + } + + [Test] + public async Task VerifyAuthenticationFailsBasedOnConfig() + { + var context = new DefaultHttpContext + { + RequestServices = this.requestService.Object + }; + + context.Request.Headers.Authorization = new StringValues(JwtBearerDefaults.LocalAuthenticationScheme); + + this.cometHasStartedService.Setup(x => x.GetHasStartedAndIsReady()).Returns(new ServerStatus(true, DateTime.Now)); + await this.handler.InitializeAsync(new AuthenticationScheme(JwtBearerDefaults.LocalAuthenticationScheme, "", typeof(JwtBearerAuthenticationHandler)), context); + + this.appConfigService.Setup(x => x.IsAuthenticationSchemeEnabled(this.handler.Scheme.Name)).Returns(false); + + var result = await this.handler.AuthenticateAsync(); + + Assert.That(result.Succeeded, Is.False); + + await this.handler.ChallengeAsync(result.Properties); + + Assert.That(context.Response.StatusCode, Is.EqualTo(403)); + } + + [Test] + public async Task VerifyAuthenticationNotSucceedNorFailedWithInvalidHeader() + { + var context = new DefaultHttpContext + { + RequestServices = this.requestService.Object + }; + + context.Request.Headers.Authorization = new StringValues("Invalid"); + + this.cometHasStartedService.Setup(x => x.GetHasStartedAndIsReady()).Returns(new ServerStatus(true, DateTime.Now)); + await this.handler.InitializeAsync(new AuthenticationScheme(JwtBearerDefaults.LocalAuthenticationScheme, "", typeof(JwtBearerAuthenticationHandler)), context); + + this.appConfigService.Setup(x => x.IsAuthenticationSchemeEnabled(this.handler.Scheme.Name)).Returns(true); + var result = await this.handler.AuthenticateAsync(); + + Assert.That(result.Succeeded, Is.False); + + await this.handler.ChallengeAsync(result.Properties); + + Assert.That(context.Response.StatusCode, Is.EqualTo(200)); + } + + [Test] + public async Task VerifyAuthenticationFailsWithInvalidToken() + { + var context = new DefaultHttpContext + { + RequestServices = this.requestService.Object + }; + + context.Request.Headers.Authorization = new StringValues($"{JwtBearerDefaults.LocalAuthenticationScheme} InvalidToken"); + + this.cometHasStartedService.Setup(x => x.GetHasStartedAndIsReady()).Returns(new ServerStatus(true, DateTime.Now)); + await this.handler.InitializeAsync(new AuthenticationScheme(JwtBearerDefaults.LocalAuthenticationScheme, "", typeof(JwtBearerAuthenticationHandler)), context); + + this.appConfigService.Setup(x => x.IsAuthenticationSchemeEnabled(this.handler.Scheme.Name)).Returns(true); + var result = await this.handler.AuthenticateAsync(); + + Assert.That(result.Failure, Is.Not.Null); + + await this.handler.ChallengeAsync(result.Properties); + + Assert.That(context.Response.StatusCode, Is.EqualTo(401)); + } + + [Test] + public async Task VerifyAuthenticationSuccessWithValidToken() + { + var context = new DefaultHttpContext + { + RequestServices = this.requestService.Object + }; + + var token = this.jwtTokenService.CreateToken(new AuthenticationPerson(Guid.NewGuid(), 1) + { + UserName = "admin" + }); + + context.Request.Headers.Authorization = new StringValues($"{JwtBearerDefaults.LocalAuthenticationScheme} {token}"); + + this.cometHasStartedService.Setup(x => x.GetHasStartedAndIsReady()).Returns(new ServerStatus(true, DateTime.Now)); + await this.handler.InitializeAsync(new AuthenticationScheme(JwtBearerDefaults.LocalAuthenticationScheme, "", typeof(JwtBearerAuthenticationHandler)), context); + + this.appConfigService.Setup(x => x.IsAuthenticationSchemeEnabled(this.handler.Scheme.Name)).Returns(true); + var result = await this.handler.AuthenticateAsync(); + + Assert.That(result.Succeeded, Is.True); + } + } +} diff --git a/CometServer/Authentication/Bearer/JwtBearerAuthenticationHandler.cs b/CometServer/Authentication/Bearer/JwtBearerAuthenticationHandler.cs index 792ffc89..9ba5c1c8 100644 --- a/CometServer/Authentication/Bearer/JwtBearerAuthenticationHandler.cs +++ b/CometServer/Authentication/Bearer/JwtBearerAuthenticationHandler.cs @@ -31,8 +31,6 @@ namespace CometServer.Authentication.Bearer using Carter.Response; - using CDP4Authentication; - using CometServer.Configuration; using CometServer.Extensions; using CometServer.Health; @@ -141,7 +139,7 @@ protected override async Task HandleAuthenticateAsync() try { if (!this.cometHasStartedService.GetHasStartedAndIsReady().IsHealthy - || this.appConfigService.IsAuthenticationSchemeEnabled(this.Scheme.Name)) + || !this.appConfigService.IsAuthenticationSchemeEnabled(this.Scheme.Name)) { return AuthenticateResult.NoResult(); }