I am trying to use cookie based authentication in ASP.Net Core 2.0 Web API and trying to activate that using the following code. The signin page is hosted inan separate domain than the one the app is hosted. And I have added [Authorize] attribute to the controller.
At startup I can see the service code invoked in debugger.
My expectation is that when my web client use the web api service, the middleware will detect that header does not have the cookie and will redirect the client to the login page. Yet I am able to invoke the controller freely.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options => options.AddPolicy("AllowAll",
builder => builder.SetIsOriginAllowed(s => true)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()));
services.TryAddTransient<CorsAuthorizationFilter, CorsAuthorizationFilter>();
services.AddSwaggerGen(c =>
{
c.OperationFilter<FileOperationFilter>();
c.SwaggerDoc("v1", new Info
{
Title = "Collateral Management API",
Version = "v1"
});
});
services.AddMvcCore(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"));
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.AddApiExplorer()
.AddJsonFormatters(s => s.NullValueHandling = NullValueHandling.Ignore);
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(auth =>
{
auth.Cookie.Domain = "xxx.com";
auth.Cookie.Name = "xxx";
auth.LoginPath = "/signin";
auth.AccessDeniedPath = "/signin";
});
services.AddAuthorization(auth =>
{
auth.DefaultPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
});
//...
}
and later ...
app.UseAuthentication()
LoginPathwill not be used unless the call is rejected by an authorization middleware later in the chain.[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]but that did not work either