I have added authentication to my API with the possibility to authenticate with two different authentication schemes.
Based on the format of the Auth header I forward the authentication request to the appropriate Authentication handler using a ForwardDefaultSelector
.
services.AddAuthentication(opt =>
{
opt.DefaultScheme = "ForwardScheme";
opt.DefaultChallengeScheme = "ForwardScheme";
})
.AddPolicyScheme("ForwardScheme", "ForwardScheme", options =>
options.ForwardDefaultSelector = context =>
context.Request.IsSchemeA()
? "SchemeA"
: "SchemeB")
.AddSchemeA()
.AddSchemeB();
Adding Schemes:
public static AuthenticationBuilder AddSchemeA(this AuthenticationBuilder builder)
{
builder.AddScheme<AuthenticationSchemeOptions, SchemeAHandler>(
"SchemeA", null);
return builder;
}
The forwarding seems to be working fine, I can see the request coming to the right auth handler based on the header value.
The problem is even when the auth fails, the API call is not blocked and I still get a 200 response back.
In the AuthHandler I am just returning this:
return AuthenticateResult.Fail("Authentication Failed");
Any idea what I am missing here? Thanks.
CodePudding user response:
@EnricoMassone thanks for pointing me in the right direction.
I was missing [Authorize]
attribute on my controller methods.
you can set the attribute individually on each method or you could do something like this, and it would enable authorization on all methods for all of your controllers
CodePudding user response:
If you register an authentication scheme for your application and you add the authentication middleware to the ASP.NET core request pipeline, you are basically asking the ASP.NET core framework of trying to authenticate any incoming request, by using the specified authentication scheme. This won't change, by itself, the response status code from 200 to 401.
In order for you to get a 401 response when an anonymous request gets to your server, you need to raise a so called authetication challenge
to the incoming request.
The simplest way to do that is basically requiring the request principal to be authenticated in order to execute a certain action method. To do that you simply need to decorate the action method by using the [Authorize] attribute. This way you are setting an execution policy to your action method, which allows the method execution only if the request principal is authenticated.