Skip to content

Commit

Permalink
Integration test with auth in Docker is working
Browse files Browse the repository at this point in the history
  • Loading branch information
fdonnet committed Oct 17, 2023
1 parent 3e057c4 commit 20715db
Show file tree
Hide file tree
Showing 8 changed files with 2,171 additions and 2,199 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public AccountController(IMediator mediator)
_mediator = mediator;
}

//[Authorize(Roles = "ubik_accounting_account_read")]
[Authorize(Roles = "ubik_accounting_account_read")]
[HttpGet]
[ProducesResponseType(200)]
[ProducesResponseType(typeof(CustomProblemDetails), 500)]
Expand All @@ -31,6 +31,7 @@ public async Task<ActionResult<IEnumerable<GetAllAccountsResult>>> GetAccounts()
return Ok(results);
}

[Authorize(Roles = "ubik_accounting_account_read")]
[HttpGet("{id}")]
[ProducesResponseType(200)]
[ProducesResponseType(typeof(CustomProblemDetails), 404)]
Expand Down
1 change: 0 additions & 1 deletion src/Ubik.Accounting.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ public static void Main(string[] args)
o.RequireHttpsMetadata = bool.Parse(builder.Configuration["Keycloack:RequireHttpsMetadata"]!);
});


// Add services to the container.
var serverVersion = new MariaDbServerVersion(new Version(11, 1, 2));
builder.Services.AddDbContextFactory<AccountingContext>(
Expand Down
87 changes: 87 additions & 0 deletions tests/Ubik.Accounting.Api.Tests.Integration/Auth/AuthHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;

namespace Ubik.Accounting.Api.Tests.Integration.Auth
{
internal static class AuthHelper
{
internal async static Task<string> GetAccessTokenReadOnly()
{
using var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, Environment.GetEnvironmentVariable("Keycloack__TokenUrl"));

var collection = new List<KeyValuePair<string, string>>
{
new("grant_type", "password"),
new("client_id", "ubik_accounting_api"),
new("username", "testro"),
new("password", "test"),
new("client_secret", "GQEyHjeBUThKta1eItucb5LFGj5Hduwd")
};

var content = new FormUrlEncodedContent(collection);
request.Content = content;

var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();

var result = await response.Content.ReadFromJsonAsync<TokenObjFromKeycloack>();

return result!.AccessToken;
}

internal async static Task<string> GetAccessTokenReadWrite()
{
using var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, Environment.GetEnvironmentVariable("Keycloack__TokenUrl"));

var collection = new List<KeyValuePair<string, string>>
{
new("grant_type", "password"),
new("client_id", "ubik_accounting_api"),
new("username", "testrw"),
new("password", "test"),
new("client_secret", "GQEyHjeBUThKta1eItucb5LFGj5Hduwd")
};

var content = new FormUrlEncodedContent(collection);
request.Content = content;

var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();

var result = await response.Content.ReadFromJsonAsync<TokenObjFromKeycloack>();

return result!.AccessToken;
}

internal async static Task<string> GetAccessTokenNoRole()
{
using var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, Environment.GetEnvironmentVariable("Keycloack__TokenUrl"));

var collection = new List<KeyValuePair<string, string>>
{
new("grant_type", "password"),
new("client_id", "ubik_accounting_api"),
new("username", "testnorole"),
new("password", "test"),
new("client_secret", "GQEyHjeBUThKta1eItucb5LFGj5Hduwd")
};

var content = new FormUrlEncodedContent(collection);
request.Content = content;

var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();

var result = await response.Content.ReadFromJsonAsync<TokenObjFromKeycloack>();

return result!.AccessToken;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace Ubik.Accounting.Api.Tests.Integration.Auth
{
internal class TokenObjFromKeycloack
{
[JsonPropertyName("access_token")]
public string AccessToken { get; set; } = default!;
[JsonPropertyName("Expires_in")]
public int ExpiresIn { get; set; }
[JsonPropertyName("refresh_expires_in")]
public int RefreshExpiresIn { get; set; }
[JsonPropertyName("refresh_token")]
public string RefreshToken { get; set; } = default!;
[JsonPropertyName("token_type")]
public string TokenType { get; set; } = default!;
[JsonPropertyName("not_before_policy")]
public int NotBeforePolicy { get; set; }
[JsonPropertyName("session_state")]
public string SessionState { get; set; } = default!;
[JsonPropertyName("scope")]
public string Scope { get; set; } = default!;

}
}
Original file line number Diff line number Diff line change
@@ -1,57 +1,39 @@
using FluentAssertions;
using Microsoft.AspNetCore.Mvc.Testing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Threading.Tasks;
using Ubik.Accounting.Api.Data;
using Ubik.Accounting.Api.Features;
using Ubik.Accounting.Api.Models;
using static Ubik.Accounting.Api.Features.Accounts.Queries.GetAllAccounts;
using static Ubik.Accounting.Api.Features.Accounts.Queries.GetAccount;
using System.Net;
using Ubik.ApiService.Common.Exceptions;
using static Ubik.Accounting.Api.Features.Accounts.Commands.AddAccount;
using Bogus;
using System.Text.Json.Nodes;
using System.Text.Json;
using Xunit.Abstractions;
using DotNet.Testcontainers.Containers;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Org.BouncyCastle.Tls;
using Microsoft.EntityFrameworkCore.Internal;
using MediatR;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;
using static Ubik.Accounting.Api.Features.Accounts.Commands.UpdateAccount;
using Ubik.Accounting.Api.Features.Accounts.Mappers;
using static Ubik.Accounting.Api.Features.Accounts.Commands.DeleteAccount;
using System.Net.Http.Headers;
using Ubik.Accounting.Api.Tests.Integration.Auth;

namespace Ubik.Accounting.Api.Tests.Integration.Features.Accounts
{
public class AccountController_Test : BaseIntegrationTest
{
private readonly DbInitializer _testDBValues;


public AccountController_Test(IntegrationTestWebAppFactory factory) : base(factory)
{
_testDBValues = new DbInitializer();
}

[Fact]
public async Task Get_Accounts_Ok()
public async Task GetAll_Accounts_Ok()
{
//Arrange
var httpClient = Factory.CreateDefaultClient();

var accessToken = await AuthHelper.GetAccessTokenReadOnly();
httpClient.DefaultRequestHeaders.Authorization =new AuthenticationHeaderValue("Bearer", accessToken);

//Act
var response = await httpClient.GetAsync("/Account");
var result = await response.Content.ReadFromJsonAsync<IEnumerable<GetAllAccountsResult>>();
Expand All @@ -63,12 +45,43 @@ public async Task Get_Accounts_Ok()
.And.AllBeOfType<GetAllAccountsResult>(); ;
}

[Fact]
public async Task GetAll_401_NotAuth()
{
//Arrange
var httpClient = Factory.CreateDefaultClient();
//Act
var response = await httpClient.GetAsync("/Account");

//Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}

[Fact]
public async Task GetAll_403_NoRole()
{
//Arrange
var httpClient = Factory.CreateDefaultClient();
var accessToken = await AuthHelper.GetAccessTokenNoRole();

httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

//Act
var response = await httpClient.GetAsync("/Account");

//Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
}

[Fact]
public async Task Get_Account_Ok()
{
//Arrange
var httpClient = Factory.CreateDefaultClient();

var accessToken = await AuthHelper.GetAccessTokenReadOnly();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

//Act
var response = await httpClient.GetAsync($"/Account/{_testDBValues.AccountId1}");
var result = await response.Content.ReadFromJsonAsync<GetAccountResult>();
Expand All @@ -81,12 +94,44 @@ public async Task Get_Account_Ok()
.And.Match<GetAccountResult>(x => x.Code == "1020");
}

[Fact]
public async Task Get_401_NoAuth()
{
//Arrange
var httpClient = Factory.CreateDefaultClient();

//Act
var response = await httpClient.GetAsync($"/Account/{_testDBValues.AccountId1}");

//Assert
response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
}

[Fact]
public async Task Get_403_NoRole()
{
//Arrange
var httpClient = Factory.CreateDefaultClient();

var accessToken = await AuthHelper.GetAccessTokenNoRole();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

//Act
var response = await httpClient.GetAsync($"/Account/{_testDBValues.AccountId1}");

//Assert
response.StatusCode.Should().Be(HttpStatusCode.Forbidden);
}

[Fact]
public async Task Get_ProblemDetails_AccountIdNotFound()
{
//Arrange
var httpClient = Factory.CreateDefaultClient();

var accessToken = await AuthHelper.GetAccessTokenReadOnly();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

//Act
var response = await httpClient.GetAsync($"/Account/{Guid.NewGuid()}");
var result = await response.Content.ReadFromJsonAsync<CustomProblemDetails>();
Expand Down Expand Up @@ -213,6 +258,9 @@ public async Task Put_Account_Ok()
//Arrange
var httpClient = Factory.CreateDefaultClient();

var accessToken = await AuthHelper.GetAccessTokenReadOnly();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

//Act
var fakeAc = FakeGenerator.GenerateAccounts(1, _testDBValues.AccountGroupId1).First();
var fake = fakeAc.ToAddAccountResult();
Expand Down Expand Up @@ -248,6 +296,9 @@ public async Task Put_ProblemDetails_AccountEmptyFields()
//Arrange
var httpClient = Factory.CreateDefaultClient();

var accessToken = await AuthHelper.GetAccessTokenReadOnly();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

//Act
var fakeAc = FakeGenerator.GenerateAccounts(1, _testDBValues.AccountGroupId1).First();
var fake = fakeAc.ToAddAccountResult();
Expand Down Expand Up @@ -281,6 +332,9 @@ public async Task Put_ProblemDetails_AccountTooLongFields()
//Arrange
var httpClient = Factory.CreateDefaultClient();

var accessToken = await AuthHelper.GetAccessTokenReadOnly();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

//Act
var fakeAc = FakeGenerator.GenerateAccounts(1, _testDBValues.AccountGroupId1).First();
var fake = fakeAc.ToAddAccountResult();
Expand Down Expand Up @@ -313,6 +367,9 @@ public async Task Put_ProblemDetails_AccountCodeExistsWithDifferentId()
//Arrange
var httpClient = Factory.CreateDefaultClient();

var accessToken = await AuthHelper.GetAccessTokenReadOnly();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

//Act
var fakeAc = FakeGenerator.GenerateAccounts(1, _testDBValues.AccountGroupId1).First();
var fake = fakeAc.ToAddAccountResult();
Expand Down Expand Up @@ -344,6 +401,9 @@ public async Task Put_ProblemDetails_AccountIdNotFound()
//Arrange
var httpClient = Factory.CreateDefaultClient();

var accessToken = await AuthHelper.GetAccessTokenReadOnly();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

//Act
var fakeAc = FakeGenerator.GenerateAccounts(1, _testDBValues.AccountGroupId1).First();
var fake = fakeAc.ToAddAccountResult();
Expand Down Expand Up @@ -374,6 +434,9 @@ public async Task Put_ProblemDetails_AccountModifiedByAnotherProcess()
//Arrange
var httpClient = Factory.CreateDefaultClient();

var accessToken = await AuthHelper.GetAccessTokenReadOnly();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

//Act
var fakeAc = FakeGenerator.GenerateAccounts(1, _testDBValues.AccountGroupId1).First();
var fake = fakeAc.ToAddAccountResult();
Expand Down Expand Up @@ -449,25 +512,5 @@ public async Task Del_ProblemDetails_AccountIdEmpty()
.And.BeOfType<CustomProblemDetails>()
.And.Match<CustomProblemDetails>(x => x.Errors.First().Code == "VALIDATION_ERROR");
}

private async Task<string> GetAccessToken()
{
var tokenUrl = Environment.GetEnvironmentVariable("TokenUrl");
var httpClient = Factory.CreateDefaultClient();
httpClient.DefaultRequestHeaders.Add("Content-Type", "application/x-www-form-urlencoded");

var keyValuesList = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", "admin"),
new KeyValuePair<string, string>("password", "admin")
};
var content = new FormUrlEncodedContent(keyValuesList);

var response = await httpClient.PutAsync(tokenUrl, content);

return await response.Content.ReadAsStringAsync();

}
}
}
Loading

0 comments on commit 20715db

Please sign in to comment.