Following the answer on this question, I have added authorization on everything by default, using the following code:
public void ConfigureServices(IServiceCollection aServices)
{
aServices.AddMvc(options =>
{
var lBuilder = new AuthorizationPolicyBuilder().RequireAuthenticatedUser();
var lFilter = new AuthorizeFilter(lBuilder.Build());
options.Filters.Add(lFilter);
});
aServices.AddMvc();
}
public void Configure(IApplicationBuilder aApp, IHostingEnvironment aEnv, ILoggerFactory aLoggerFactory)
{
aApp.UseCookieAuthentication(options =>
{
options.AuthenticationScheme = "Cookies";
options.AutomaticAuthentication = true;
});
}
However when someone tries to access something unauthorized, it returns a (what seems a default) redirect URL (http://foo.bar/Account/Login?ReturnUrl=%2Fapi%2Ffoobar%2F).
I want it to return a HTTP 401 only, instead of a redirect.
How can I do this in ASP.NET 5 for a WebAPI?
By the url you get redirected to I assume you're using cookie authentication.
You should get the desired results by setting the
LoginPath
property of theCookieAuthenticationOptions
to null or empty as described by one of the users.It was probably working back then but it's not working anymore (because of this change).
I've submitted a bug on GitHub for this.
I'll update the answer once it gets fixed.
I had a similar problem. I solved this adding by manually the services.
ConfigureServices method:
Configure method:
I am using aspnet core 2.0, IdentityServer 4 and aspnet identity.
I had with this problem in an Angular2 + ASP.NET Core application. I managed to fix it in the following way:
If this is not working for you, you can try with the following method instead:
Update for Asp.Net Core 2.0
Cookie options are now configured in the following way:
Setting LoginPath = "" or null no longer works on Version 1.1.0.0. So here's what I did:
Be aware, you should not use the
CookieAuthentication
only if you want to use your own Authentication Mechanism for example bypassing theIdentity
provider which not the case for most of us.The default
Identity
provider use theCookieAuthenticationOptions
behind the scene, you can configure it like the below.Tested in version
1.0.0
in case it helps, below is my answer - with dotnet 1.0.1
its based on Darkseal's answer except I had to add the line ctx.Response.WriteAsync() to stop the redirect to the default 401 URL (Account/Login)