3

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()
5
  • Have you configured authorization? The LoginPath will not be used unless the call is rejected by an authorization middleware later in the chain. Commented Jan 3, 2018 at 16:54
  • make sure app.UseAuthentication is before app.UseMvc. if testing on localhost then leave out the domain name. might also try make the cookie name the same as the authentication scheme Commented Jan 3, 2018 at 17:09
  • @Pace Could you please elaborate what you mean by configuring authorization - following your comment I also tried [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] but that did not work either Commented Jan 3, 2018 at 17:22
  • I elaborated in an answer since it was a bit much for a comment. Commented Jan 3, 2018 at 17:35
  • Is it solved ? If not can you add the code of your middleware ? and the controller code ? Are you using IHttpContextAccessor in your controller constructor to access to your cookies ? If not you need to add it. Commented Apr 22, 2018 at 17:24

1 Answer 1

5

Try adding:

services.AddAuthorization(options =>
{
    options.DefaultPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
});

After services.AddMvc()

EDIT

Given the way you are adding MVC can you try:

// requires: using Microsoft.AspNetCore.Authorization;
//           using Microsoft.AspNetCore.Mvc.Authorization;
services.AddMvcCore(config =>
{
    var policy = new AuthorizationPolicyBuilder()
                     .RequireAuthenticatedUser()
                     .Build();
    config.Filters.Add(new AuthorizeFilter(policy));
});

AddMvcCore doesn't add the authorization services by default. You will also need to do AddMvcCore(...).AddAuthorization()

Sign up to request clarification or add additional context in comments.

9 Comments

Tried but did not work. I use services.AddMvcCore(options => options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAll"))) .AddApiExplorer() .AddJsonFormatters(s => s.NullValueHandling = NullValueHandling.Ignore);
Added something else to try
I am getting exception now upon invoking an api No service for type 'Microsoft.AspNetCore.Authorization.Policy.IPolicyEvaluator' has been registered. I edited my question to provide full relevant code in ConfigureServices I really appreciate that you continue toe assist me
I didn't realize that AddMvcCore doesn't add the authorization services by default. You will need to do AddMvcCore(...).AddAuthorization().
AddMvcCore(...).AddAuthorization() is what I needed with the policy being configured in the AddMvcCore builder method, not the AddAuthorization
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.