Custom schemes - Xabaril/Acheve.TestHost GitHub Wiki
Default Scheme
By default, Acheve.TestHost uses the TestServer scheme.
This is Ok if you have in your API Authorize attributes or Authorization Policies that not specify the AuthenticationSchemes to use.
Custom Scheme
But in some scenarios, where you have more than one authentication schema configured, you may want to ensure that the authentication and authorization happens against a specific authentication scheme.
We can do this by setting the AuthenticationSchemes in the Authorize attribute or in the authorization policy.
[Authorize(AuthenticationSchemes = "Bearer")]
[HttpGet("scheme")]
public IActionResult ValuesWithSchema()
{
return Ok(new[] { "Value1", "Value2" });
}
In this case, we should register the TestServer authentication handler with the scheme we expect to use:
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(TestServerDefaults.AuthenticationScheme)
.AddTestServer("Bearer");
var mvcCoreBuilder = services.AddMvcCore()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
ApiConfiguration.ConfigureCoreMvc(mvcCoreBuilder);
}
And we must include the scheme we want to use when we use the .WithIdentity extension method:
[Fact]
public async Task Authorized_User_Should_Get_200_Using_A_Specific_Scheme()
{
var response = await _fixture.Server.CreateHttpApiRequest<ValuesController>(controller => controller.ValuesWithSchema())
.WithIdentity(Identities.User, scheme: "Bearer")
.GetAsync();
await response.IsSuccessStatusCodeOrThrow();
}