Adds authentication support for integration testing

This commit is contained in:
BinaryAlley committed 2024-11-16 15:49:24 +02:00
1 parent f2703b86c5
commit 5aa7a5f672
33 files changed
+671 -227

No files matched your search

@@ -1,49 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Common.Fixtures;
/// <summary>
/// Provides JWT token generation functionality for testing purposes.
/// </summary>
[ExcludeFromCodeCoverage]
public class JwtFixture
{
private static readonly string s_secretKey = "test-key-thats-at-least-32-chars-long-for-jwt";
/// <summary>
/// Generates a JWT token for testing with the specified username and optional roles.
/// </summary>
/// <param name="username">The username to include in the token claims.</param>
/// <param name="roles">Optional array of roles to include in the token claims.</param>
/// <returns>A JWT token string that can be used for authentication in tests.</returns>
public static string GenerateJwtToken(string username, string[]? roles = null)
{
byte[] key = Encoding.ASCII.GetBytes(s_secretKey);
List<Claim> claims =
[
new(ClaimTypes.Name, username),
new(ClaimTypes.NameIdentifier, username)
];
if (roles?.Length > 0)
claims.AddRange(roles.Select(role => new Claim(ClaimTypes.Role, role)));
JwtSecurityToken token = new(
issuer: "test-issuer",
audience: "test-audience",
claims: claims,
expires: DateTime.UtcNow.AddHours(1),
signingCredentials: new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
@@ -0,0 +1,116 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
using Lumina.Contracts.Requests.Authentication;
using Lumina.Contracts.Responses.Authentication;
using Lumina.DataAccess.Core.UoW;
using Lumina.Infrastructure.Core.Security;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.IntegrationTests.Common.Setup;
// <summary>
/// Factory that extends <see cref="LuminaApiFactory"/> to provide authenticated HTTP clients for testing.
/// </summary>
[ExcludeFromCodeCoverage]
public class AuthenticatedLuminaApiFactory : LuminaApiFactory, IDisposable
{
private readonly HashService _hashService;
private readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
/// <summary>
/// Gets the username of the currently created test user.
/// </summary>
public string? TestUsername { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="AuthenticatedLuminaApiFactory"/> class.
/// </summary>
public AuthenticatedLuminaApiFactory()
{
_hashService = new HashService();
}
/// <summary>
/// Creates an HTTP client with authentication headers and a test user
/// </summary>
/// <returns>An HTTP client configured with auth headers</returns>
public async Task<HttpClient> CreateAuthenticatedClientAsync()
{
HttpClient client = CreateClient();
TestUsername = $"testuser_{Guid.NewGuid()}";
// add the X-Forwarded-For header
client.DefaultRequestHeaders.Add("X-Forwarded-For", $"192.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}.{Random.Shared.Next(0, 255)}");
// perform authentication
await CreateAndAuthenticateUser(client);
return client;
}
/// <summary>
/// Creates and authenticates a test user.
/// </summary>
/// <param name="client">The HTTP client to configure with auth.</param>
/// <returns>The created user entity.</returns>
private async Task<UserEntity> CreateAndAuthenticateUser(HttpClient client)
{
using IServiceScope scope = Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
// create test user
UserEntity user = new()
{
Username = TestUsername!,
Password = _hashService.HashString("TestPass123!"),
Libraries = [],
Created = DateTime.UtcNow
};
dbContext.Users.Add(user);
await dbContext.SaveChangesAsync();
// authenticate user
LoginRequest loginRequest = new(
Username: user.Username,
Password: "TestPass123!"
);
HttpResponseMessage loginResponse = await client.PostAsJsonAsync("/api/v1/auth/login", loginRequest);
string content = await loginResponse.Content.ReadAsStringAsync();
LoginResponse? result = JsonSerializer.Deserialize<LoginResponse>(content, _jsonOptions);
// set auth header for subsequent requests
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result!.Token);
return user;
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public new void Dispose()
{
using IServiceScope scope = Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity? user = dbContext.Users.FirstOrDefault(u => u.Username == TestUsername);
if (user is not null)
{
dbContext.Users.Remove(user);
dbContext.SaveChanges();
}
}
}
@@ -25,6 +25,9 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
{
private readonly SqliteConnection _connection;
private const string TEST_ENCRYPTION_KEY = "MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=";
private static byte s_IpClass = 25;
public static byte IpClass => s_IpClass++;
/// <summary>
/// Initializes a new instance of the <see cref="LuminaApiFactory"/> class.
@@ -54,6 +57,8 @@ public class LuminaApiFactory : WebApplicationFactory<Program>, IDisposable
config.AddInMemoryCollection(initialData: new Dictionary<string, string?>
{
["JwtSettings:SecretKey"] = "test-key-thats-at-least-32-chars-long-for-jwt",
["JwtSettings:Issuer"] = "test-issuer",
["JwtSettings:Audience"] = "test-audience",
["EncryptionSettings:SecretKey"] = TEST_ENCRYPTION_KEY // base64 encoded test key
});
});