Skip to content

Latest commit

 

History

History
63 lines (42 loc) · 2.74 KB

README.md

File metadata and controls

63 lines (42 loc) · 2.74 KB

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.