I'm creating a simple authentication handler to be used with an ASP.NET Core Web API using the instructions of an article. The following code is a part of this work.
public class CustomAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOptions>
{
//Constructors and fields
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
//Validation of bearer token
//No awaitable method calls
}
}
Although this HandleAuthenticateAsync()
method is marked as async
, it doesn't actually await anything inside the method body at all. So, my questions are,
- Do I really need to use a method decorated with async for this? Would it affect the application if I omitted the async keyword?
- Can I rearrange this method which returns a
Task<AuthenticateResult>
in the following way without violating the best practices described in docs.
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
return new Task<AuthenticateResult>(() =>
{
//Token validation
});
}
CodePudding user response:
Do I really need to use a method decorated with async for this? Would it affect the application if I omitted the async keyword?
I recommend that you do keep the async
keyword, and use a #
to silence the compiler warning. With task-returning methods, any exceptions should be caught and placed on the returned task, and async
will do that for you so you don't have to write that code yourself.
Can I rearrange this method which returns a Task in the following way
No. You should never use the Task
constructor.
If you don't want to use async
, then return results using Task.FromResult
and return exceptions using Task.FromException
.
CodePudding user response:
You don't need to decorate that method with async at all. Only if you will have something to be awaited there.
Your second point - you can totally do that but it hinders readability.
You can just follow the tutorials, which say the following: If something is wrong and Authentication cannot be done, return the following:
return Task.FromResult(AuthenticateResult.Fail("Cannot Auth"));
If everything is good, just return
return Task.FromResult(AuthenticateResult.Success(ticket));
The ticket being the AuthenticationTicket
for the principal authenticating.
More info here: Authentication scheme in ASP.NET Core