asp.net core SignInAsync method not Authenticating

Viewed 187

I have [authorize] attribute at the top of my admin controller. When I run the following code from my sign in page:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Name, vm.Email)
};

var claimsIdentity = new ClaimsIdentity(claims, 
    CookieAuthenticationDefaults.AuthenticationScheme);

await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
    new ClaimsPrincipal(claimsIdentity));

Everything runs fine. However it doesn't seem to be signing in the user because the admin controller sends the user back to the sign in page and User.Identity.IsAuthenticated is false.

EDIT: Here are my Configure and ConfigureServices methods:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddDistributedMemoryCache();

    services.AddSession(options =>
    {
        // Set a short timeout for easy testing.
        // options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
    });


    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddDbContext<myDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("myDb")));

    services.AddScoped<AccountsRepository>();

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.AccessDeniedPath = new PathString("/Account/AccessDenied");
            options.LoginPath = new PathString("/Account/SignIn");
            options.LogoutPath = new PathString("/Home/SignOut");
        });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();
    app.UseSession();

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