Authorization means the process that decides what a user is able to do. Let’s take an example of user Adam who’s able to create a document library, add documents, do the edit and delete them. But Bob might only be authorized to read the documents in a single library.
1. Authorization In Asp.Net
Part IV
Resource Based Authorization
Today we will be discussing resource based authorization.
Often authorization is based upon the accessed resource . E.g. a document might have an author
property. So only the author would be allowed to update it; the resource must be loaded from the
document repository before an authorization access can be made. This can't be done with an Authorize
attribute, as feature evaluation takes place before data binding and before the code to load a resource
runs inside an action. Instead of the declarative authorization, the attribute method, we must use
impervious authorization, where a developer calls upon an authorize function within his own code.
Authorizing within a code
Authorization is executed as a service, IAuthorizationService, registered in the service collection and
available via dependency injection for Controllers to approach.
public class DocumentController : Controller
{
IAuthorizationService _authorizationService;
2. public DocumentController(IAuthorizationService authorizationService)
{
_authorizationService = authorizationService;
}
}
IAuthorizationService has 2 methods: in one, you pass the resource and the policy name and in the
other, you pass the resource and a list of requirements to assess.
Task<bool> AuthorizeAsync(ClaimsPrincipal user,
object resource,
IEnumerable<IAuthorizationRequirement> requirements);
Task<bool> AuthorizeAsync(ClaimsPrincipal user,
object resource,
string policyName);
To call upon the service load resource within action then call the AuthorizeAsync overload you
require. e.g.
public async Task<IActionResult> Edit(Guid documentId)
{
Document document = documentRepository.Find(documentId);
if (document == null)
{
return new HttpNotFoundResult();
}
if (await authorizationService.AuthorizeAsync(User, document, "EditPolicy"))
{
3. return View(document);
}
else
{
return new ChallengeResult();
}
}
Writing a resource based handler
Now to write a handler for resource based authorization is not very much different to write a plain
requirements handler. You create a requirement, and then execute a handler for the requirement, then
specify the requirement as before and also the resource type.
Therefore, a handler which might accept a Document resource would look as below:
public class DocumentAuthorizationHandler : AuthorizationHandler<MyRequirement, Document>
{
public override Task HandleRequirementAsync(AuthorizationHandlerContext context,
MyRequirement requirement,
Document resource)
{
// Ratify the requirement against the resource and identity.
return Task.CompletedTask;
}
}
Don’t forget you also need to list your handler in the ConfigureServices method;
services.AddSingleton<IAuthorizationHandler, DocumentAuthorizationHandler>();
Requirements
If you want to make decisions based on operations such as read, write, update and delete, you can use
the OperationAuthorizationRequirement in the Microsoft.AspNetCore.Authorization.Infrastructure
namespace. This previously built requirement class helps you to write a single handler which has a set
parameterized operation name, rather than develop individual classes for each operation. To utilize it
provide some operation names:
4. public static class Operations
{
public static OperationAuthorizationRequirement Create =
new OperationAuthorizationRequirement { Name = "Create" };
public static OperationAuthorizationRequirement Read =
new OperationAuthorizationRequirement { Name = "Read" };
public static OperationAuthorizationRequirement Update =
new OperationAuthorizationRequirement { Name = "Update" };
public static OperationAuthorizationRequirement Delete =
new OperationAuthorizationRequirement { Name = "Delete" };
}
Your handler could then be executed as follows, using a hypothetical Document class as the resource;
public class DocumentAuthorizationHandler :
AuthorizationHandler<OperationAuthorizationRequirement, Document>
{
public override Task HandleRequirementAsync(AuthorizationHandlerContext
OperationAuthorizationRequirement ,
Document resource)
{
// Validate the operation using the resource, the identity and
// the Name property value from the requirement.
return Task.CompletedTask;
}
}
You can view the handler works upon OperationAuthorizationRequirement. The code inside the
handler must take the Name property of the supplied need into account when making its evaluations.
5. To call an operational resource handler you are required to specify the operation when calling
AuthorizeAsync in your action. For example
if (await authorizationService.AuthorizeAsync(User, document, Operations.Read))
{
return View(document);
}
else
{
return new ChallengeResult();
}
This example checks if the user is able to perform the read function for the current document. If
authorization succeeds the view for the document will be returned.
If you want to learn ASP.Net and perfect yourself in .NET training, our CRB Tech Solutions would be
of great support for you. Join us with our updated program in ASP.Net course.
Stay connected to CRB Tech reviews for more technical optimization and other resources.