JH-Sen-Ren
JH-Sen-Ren

Reputation: 279

.NET Core 2.2 sends out authentication cookie but doesn't recognise it

I'm using .NET Core 2.2 Web API with an Angular 8 SPA. The Angular bit is unimportant to the question, but the important bit to note is that I'm not using MVC.

I'm also using EntityFramework Identity to authenticate users with Cookies.

For my testing, I'm using Insomnia.

My endpoint to log in works, and produces a cookie, which is stored by Insomnia and resent on future requests.

My issues start here. I currently cannot get the application to recognise the cookie and my API responds with 401 Unauthorized to any endpoints marked with the [Authorize] attribute despite having a valid cookie which has a life of 7 days.

Here's my Startup.cs file:

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddSwaggerGen(x =>
        {
            // stuff
        });

        services.AddDbContext<SensoLicensingContext>(options => {
            // stuff
        });

        services.AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<LicencingContext>()
            .AddDefaultTokenProviders();

        services.ConfigureApplicationCookie(options =>
        {
            options.Events.OnRedirectToLogin = context =>
            {
                context.Response.Headers["Location"] = context.RedirectUri;
                context.Response.StatusCode = 401;
                return Task.CompletedTask;
            };
        });

        services.AddTransient<IEmailSender, EmailSender>();
        services.Configure<AuthMessageSenderOptions>(options =>
            Configuration.GetSection("SendGridEmailSettings").Bind(options));

        services
            .AddMvcCore()
            .AddApiExplorer()
            .AddAuthorization()
            .AddFormatterMappings()
            .AddJsonFormatters()
            .AddCors()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie();

            // In production, the Angular files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });
    }

    public void Configure(IApplicationBuilder app, 
                IHostingEnvironment env, 
                UserManager<ApplicationUser> userManager,
                RoleManager<IdentityRole> roleManager,
                LicensingContext dbContext)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseSwagger();
            app.UseSwaggerUI(x =>
            {
                x.SwaggerEndpoint(Constants.SwaggerEndPointUrl, Constants.SwaggerEndPointName);
            });
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
            app.UseHttpsRedirection();
        }

        app.UseStaticFiles();
        app.UseSpaStaticFiles();
        app.UseAuthentication();

        dbContext.Database.EnsureCreated();
        IdentityDataInitializer.SeedData(userManager, roleManager);

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");
        });

        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501

            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
            }
        });
    }

I have a feeling the issue lies in this part, either my ordering or it's in the wrong place entirely, but I'm relatively new to .NET Core so I'm not sure:

services
    .AddMvcCore()
    .AddApiExplorer()
    .AddAuthorization()
    .AddFormatterMappings()
    .AddJsonFormatters()
    .AddCors()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();

Any help would be kindly appreciated.

Upvotes: 0

Views: 167

Answers (1)

Kahbazi
Kahbazi

Reputation: 15015

Since you are using ASP.NET Identity, you do not need this code

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie();

Authentication services is already added to your services with services.AddIdentity<ApplicationUser, IdentityRole>

Upvotes: 1

Related Questions