0

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

  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.

2
  • 1
    Those changes are all safe. Commented Dec 6, 2022 at 20:23
  • This question actually seems to be "how to I add 'async' to a method that returns a Task?" There's nothing special about the Authorization code here. Commented Dec 6, 2022 at 20:25

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.