AspNetAuthorizationWorkshop
AspNetAuthorizationWorkshop copied to clipboard
Add Unit Tests for Authorization
This was a great video and sample project for understanding the new authorization classes available to dotnet core. Thanks for putting it together. I would love to see unit tests for the controllers, handlers etc...
Amended info... I found an example of unit testing custom authorization here: https://github.com/henningst/ASPNETCore-AuthorizationDemo
One of my last open ended questions is with unit testing the Controllers. I have a moq IAuthorizationService created and I pass that into the constructor. However, that really is not testing if the controllers have the write policies or authorizationService logic correct. Do you have suggestions for unit testing this?
So to answer how, before I get some time to actually add examples;
// Arrange
var authorizationService = BuildAuthorizationService(services =>
{
services.AddAuthorization(options =>
{
options.AddPolicy("Basic", policy => policy.RequireClaim("Permission", "CanViewPage"));
});
});
var user = new ClaimsPrincipal(
new ClaimsIdentity(new Claim[] { new Claim("Permission", "CanViewPage") }));
// Act
var allowed = await authorizationService.AuthorizeAsync(user, "Basic");
// Assert
Assert.True(allowed);
Testing imperative code inside the controller would mean mocking up a lot more pieces, I'll have to think on the best way to do this.