简体   繁体   中英

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

I followed the code examples on https://learn.microsoft.com/en-us/as.net/core/security/authorization/policies?view=as.netcore-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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM