Skip to content

jabbera/aspnetcore-testing-role-handler

Repository files navigation

AspNetCore.Testing.Authentication.ClaimInjector

Build Status Test Status Coverage NuGet

Excercising claim based logic using Microsoft.AspNetCore.Mvc.Testing is now as simple as:

    [Fact]
    public async Task RoleCustomizationWorksTest()
    {
        this._factory.RoleConfig.Roles = new[] {"Reader"};

        var client = _factory.CreateClient();

        var response = await client.GetAsync("api/Values/RequireRoleReader");

        response.EnsureSuccessStatusCode();
    }

    [Fact]
    public async Task NoAuthorizationHeaderReturnsUnauthorizedTest()
    {
        this._factory.RoleConfig.AnonymousRequest = true;

        var client = _factory.CreateClient();

        var response = await client.GetAsync("api/Values/AllowAuthorized");

        Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
    }


    private readonly CustomRoleWebApplicationFactory<Startup> _factory;

    public UnitTests(CustomRoleWebApplicationFactory<Startup> factory)
    {
        this._factory = factory;
        this._factory.RoleConfig.Reset();
    }

For more examples see the unit tests here.

After learning about this great new library Microsoft.AspNetCore.Mvc.Testing I was excited to try it. Then I found out it has little to little to no built in support for testing controllers with Role based Authorization.

But there are workarounds (they all stink):

  • make controllers anonymous for integration testing
  • using integrated windows auth
  • host a separate identity server

None of these are both simple and allow for exercising the role based logic without a ton of complexity. This solution solves that.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages