0

I must be missing something. Note that I don't use Identity. I followed the Configuration part of this page

In my startup.cs file:

// in public void ConfigureServices(IServiceCollection services)
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.LoginPath = new PathString("/account/login/");
        options.AccessDeniedPath = new PathString("/account/forbidden/");
        options.SlidingExpiration = true;
        options.ExpireTimeSpan = TimeSpan.FromHours(336);
    });

// in public void Configure(IApplicationBuilder app, IHostingEnvironment env)
app.UseAuthentication();

Then I have some login logic that ends by

await _httpContextAccessor.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, 
                new AuthenticationProperties {IsPersistent = true});

This works fine and creates the desired cookies.

What I don't understand is how to enforce authentication for specific end points? Previously I would add [AllowAnonymous] on the end point to say it was ok to be not authenticated. But here, it doesn't seem to know if I'm signed in or not.

1) What's the best way to configure my app so that you have to be authenticated to access them?

2) How to know if a user is authenticated? (from a controller)

3) I know I could implement all this via a middleware but I would be surprised there isn't a built-in way to do it. Am I wrong?

dyesdyes
  • 1,147
  • 3
  • 24
  • 39
  • Where is your `app.UseAuthentication();` in relation to `app.UseMvc()`? – Kirk Larkin Sep 12 '18 at 11:34
  • just before app.UseMvc() – dyesdyes Sep 12 '18 at 12:08
  • Ok, that rules out the first possibility then. What happens if you add `[Authorize]` to one of your endpoints? How have you determined that *it doesn't seem to know if I'm signed in or not*? – Kirk Larkin Sep 12 '18 at 12:28
  • This was the issue. I thought I needed to put [AllowAnonymous] on the anonymous ones and the others were by default [Authorize]... Thanks! Is it possible to make the default [Authorize]? – dyesdyes Sep 12 '18 at 12:39
  • Possible duplicate of [MVC Core How to force / set global authorization for all actions?](https://stackoverflow.com/questions/36413476/mvc-core-how-to-force-set-global-authorization-for-all-actions) – Kirk Larkin Sep 12 '18 at 12:42

0 Answers0