Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Policy-based authorization in ASP.NET Core (async)

I followed the code examples on https://learn.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-7.0#use-a-handler-for-one-requirement

This all appears to work, but in order to use async/await calls I had to make some changes to the example provided by Microsoft and as this is security related I a little unsure and would appreciate some clarification.

Basically the changes I made were

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. Changed "Task" to "async TASK" on function defination
  2. Changed "return Task.CompletedTask" to just "return;" (1st instance)
  3. Remove the 2nd "return Task.CompletedTask" at the end of the function as as dont think its needed
      protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, SystemRoleRequirement2 requirement)
        {
            if (!context.User.HasClaim(c => c.Type == ClaimTypes.Name)) { return; } // Task.CompletedTask;
            var Result = (await _idb.QueryAsync<int>(cSQL.Security.SystemRoleAccess2, "SecurityReadOnly", new { UserID = context.User.ReadID(), requirement.SystemRoleIDs }))
                .SingleOrDefault();



           if (Result > 0) context.Succeed(requirement);
            //return Task.CompletedTask;
        }

Can anyone confirm that this is the correct way to implement the security handler with await calls.

>Solution :

Given a method

private Task Foo(string input)
{
    if (input is null)
    {
        return Task.Complete;
    }

    input += " is processed";
    return Task.Complete;
}

The equivalent with async would be

private async Task Foo(string input)
{
    if (input is null)
    {
        return;
    }

    input += " is processed";
    return; // not needed as it's the last statement
}

So yes, your modifications are correct.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading