Around 2.5 years back I had written about custom authorization on MVC Custom authorization on class, action/function, code, area level under Asp.Net MVC application, there are few approaches which are changed in Core version for authorization. Like Authorization filter approach is discouraged since it cannot be unit tested. I believe this is right step but also global or basic authentication could still be driven by Attribute due to enhancing simplicity on codes by focusing on the primary objective rather than writing authorization check everywhere.
The whole approach and usage remain same from the original Post, in this, we would be just looking into making it compatible with dotnet Core MVC. You would need to go through earlier Post to understand the approach that was taken for authorization of a user.
Also, can go through official post: https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies to understand new approach.
More of all we need to create Requirement i:e PermissionAuthorizationRequirement, Handler for authentication and AppAuthorizeAttribute attribute.
The whole approach and usage remain same from the original Post, in this, we would be just looking into making it compatible with dotnet Core MVC. You would need to go through earlier Post to understand the approach that was taken for authorization of a user.
Also, can go through official post: https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies to understand new approach.
More of all we need to create Requirement i:e PermissionAuthorizationRequirement, Handler for authentication and AppAuthorizeAttribute attribute.
Creating policy requirement
This can accept comparison type and PermissionRule that may be required for authorization. /// <summary>
/// Permission authorization requirement.
/// </summary>
/// <seealso cref="IAuthorizationRequirement" />
public class PermissionAuthorizationRequirement
: Microsoft.AspNetCore.Authorization.IAuthorizationRequirement
{
/// <summary>
/// Gets or sets the comparison mode.
/// </summary>
/// <value>
/// The comparison mode.
/// </value>
public ComparisonType ComparisonMode { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="PermissionAuthorizationRequirement"/> class.
/// </summary>
public PermissionAuthorizationRequirement()
{
ComparisonMode = ComparisonType.All;
}
/// <summary>
/// Initializes a new instance of the <see cref="PermissionAuthorizationRequirement" /> class.
/// </summary>
/// <param name="permissions">The permissions.</param>
/// <param name="comparisonType">Type of the comparison.</param>
public PermissionAuthorizationRequirement(PermissionRule[] permissions, ComparisonType comparisonType)
{
Permissions = permissions;
ComparisonMode = comparisonType;
}
/// <summary>
/// Gets the permissions.
/// </summary>
/// <value>
/// The permissions.
/// </value>
public PermissionRule[] Permissions { get; private set; }
}
Handler for authorization check of user
This would authorize the user based on saved permissions from DB and required permission to access the requested resource. using System.Linq;
/// <summary>
/// Permission authorization handler.
/// </summary>
/// <seealso cref="Microsoft.AspNetCore.Authorization.AuthorizationHandler{PermissionsAuthorizationRequirement}" />
public class PermissionAuthorizationHandler
: Microsoft.AspNetCore.Authorization.AuthorizationHandler<PermissionAuthorizationRequirement>
{
public PermissionAuthorizationHandler(ISecurityUserRepository securityUserRepository)
{
// Dependency injection to get value from repository.
SecurityUserRepository = securityUserRepository;
}
/// <summary>
/// Gets the security user repository.
/// </summary>
/// <value>
/// The security user repository.
/// </value>
public ISecurityUserRepository SecurityUserRepository { get; }
/// <summary>
/// Makes a decision if authorization is allowed based on a specific requirement.
/// </summary>
/// <param name="context">The authorization context.</param>
/// <param name="requirement">The requirement to evaluate.</param>
/// <returns>Permission check for user based on Permission requirement.</returns>
/// <exception cref="ArgumentException">New comparison type need to be included</exception>
protected override async System.Threading.Tasks.Task HandleRequirementAsync(
Microsoft.AspNetCore.Authorization.AuthorizationHandlerContext context,
PermissionAuthorizationRequirement requirement)
{
if (!context.User.Identity.IsAuthenticated)
{
return;
}
// Getting user id from claims
if (!int.TryParse(context.User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value, out int userId))
{
return;
}
// TODO: Implement caching for this
var userPermissions = await SecurityUserRepository.GetUserPermissions(userId);
var hasPermission = false;
switch (requirement.ComparisonMode)
{
case ComparisonType.All:
{
hasPermission = requirement.Permissions.All(reqPerm => userPermissions.Any(usrPerm => usrPerm == reqPerm));
break;
}
case ComparisonType.Any:
{
hasPermission = requirement.Permissions.Any(reqPerm => userPermissions.Any(usrPerm => usrPerm == reqPerm));
break;
}
default:
{
throw new System.ArgumentException("New comparison type need to be included");
}
}
if (hasPermission)
{
context.Succeed(requirement);
}
}
}
Attribute filter for invoking implementation
This would allow us to pass permission rule and optional ComparisionType for authorization of a user. using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Threading.Tasks;
/// <summary>
/// Application authorization
/// </summary>
/// <seealso cref="TypeFilterAttribute" />
public sealed class AppAuthorizeAttribute
: TypeFilterAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="AppAuthorizeAttribute"/> class.
/// </summary>
/// <param name="permissions">The permissions.</param>
public AppAuthorizeAttribute(params PermissionRule[] permissions)
: base(typeof(AppAuthorizeExecuteAttribute))
{
Arguments = new[] { new PermissionAuthorizationRequirement(permissions, ComparisonType.All) };
}
/// <summary>
/// Initializes a new instance of the <see cref="AppAuthorizeAttribute"/> class.
/// </summary>
/// <param name="comparisonType">Type of the comparison.</param>
/// <param name="permissions">The permissions.</param>
public AppAuthorizeAttribute(ComparisonType comparisonType = ComparisonType.All, params PermissionRule[] permissions)
: base(typeof(AppAuthorizeExecuteAttribute))
{
Arguments = new[] { new PermissionAuthorizationRequirement(permissions, comparisonType) };
}
/// <summary>
/// App authorize execution.
/// </summary>
/// <seealso cref="Attribute" />
/// <seealso cref="IAsyncResourceFilter" />
private sealed class AppAuthorizeExecuteAttribute
: Attribute, IAsyncResourceFilter
{
/// <summary>
/// The authorization service
/// </summary>
private readonly IAuthorizationService AuthorizationService;
/// <summary>
/// The required permissions
/// </summary>
private readonly PermissionAuthorizationRequirement RequiredPermissions;
/// <summary>
/// Initializes a new instance of the <see cref="AppAuthorizeExecuteAttribute" /> class.
/// </summary>
/// <param name="requiredPermissions">The required permissions.</param>
/// <param name="authorizationService">The authorization service.</param>
public AppAuthorizeExecuteAttribute(
PermissionAuthorizationRequirement requiredPermissions,
IAuthorizationService authorizationService)
{
RequiredPermissions = requiredPermissions;
AuthorizationService = authorizationService;
}
/// <summary>
/// Called asynchronously before the rest of the pipeline.
/// </summary>
/// <param name="context">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ResourceExecutingContext" />.</param>
/// <param name="next">The <see cref="T:Microsoft.AspNetCore.Mvc.Filters.ResourceExecutionDelegate" />. Invoked to execute the next resource filter or the remainder
/// of the pipeline.</param>
/// <returns>
/// A <see cref="T:System.Threading.Tasks.Task" /> which will complete when the remainder of the pipeline completes.
/// </returns>
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
{
var authResult = await AuthorizationService.AuthorizeAsync(
context.HttpContext.User,
null,
new PermissionAuthorizationRequirement(RequiredPermissions.Permissions, RequiredPermissions.ComparisonMode));
if (!authResult.Succeeded)
{
context.Result = new ChallengeResult();
return;
}
await next?.Invoke();
}
}
}
Registering handler and requirement in MVC
There could be multiple requirements that could be added to it, but for our global one, we need only one. service.AddScoped<IAuthorizationHandler, PermissionAuthorizationHandler>();
service.AddAuthorization(options =>
{
options.AddPolicy("PermissionAuthorization", policy =>
policy.Requirements.Add(new PermissionAuthorizationRequirement()));
});
Usage
Applying authorization to action is much more straightforward. [AppAuthorize(ComparisonType.Any, PermissionRule.CanAddBlog, PermissionRule.CanEditBlog)]
public ActionResult ViewBlog()
{
}
Authorization on code level
This is code on custom BaseController to authorize specific area of codes. This is same as the previous post just that new dotnet core custom policy is used. /// <summary>
/// Executes passed function once authorization is successful.
/// </summary>
/// <param name="func">The function.</param>
/// <param name="comparisonType">Type of the comparison.</param>
/// <param name="permissions">The permissions.</param>
/// <returns>Result based on passed function if authorization is successful.</returns>
public async Task<IActionResult> OnSuccessAuthAsync(
Func<IActionResult> func,
ComparisonType comparisonType,
params PermissionRule[] permissions)
{
var authResult = await AuthorizationService.AuthorizeAsync(
User, null, new PermissionAuthorizationRequirement(permissions, comparisonType));
if (authResult.Succeeded)
{
return func?.Invoke();
}
return Json(authResult);
}
/// <summary>
/// Executes passed function once authorization is successful.
/// </summary>
/// <param name="func">The function.</param>
/// <param name="permissions">The permissions.</param>
/// <returns>Result based on passed function if authorization is successful.</returns>
public async Task<IActionResult> OnSuccessAuthAsync(
Func<IActionResult> func,
params PermissionRule[] permissions)
{
return await OnSuccessAuthAsync(func, ComparisonType.All, permissions);
}
Comments
Post a Comment