0

I am trying to setup authentication using cookies but SignInAsync seems to not be working.

My sign method is, at the moment at least, like this:

[HttpPost] public async Task<IActionResult> Login(string username, string password) { if (username != "foo" || password != "bar") { return View(); } //Sign in var claims = new List<Claim> { new Claim("name", "admin") }; var userIdentity = new ClaimsIdentity(claims, "login"); ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity); await HttpContext.SignInAsync(principal); //Redirect return RedirectToAction("home"); } 

Home is an action with Authorize attribute. If I provide the correct username and password, I can step over the SignInAsync call with no exception seemingly called. However, upon redirection, I end up back at the login page as I am still not logged in.

Startup.cs is listed below:

public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/admin/login/"; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=home}/{action=index}/{id?}"); }); app.UseAuthentication(); } } 

What am I missing or how can I debug/get further information on what is going wrong?

1
  • 8
    app.UseAuthentication(); goes before UseMvc. Commented Mar 12, 2018 at 3:13

1 Answer 1

3

As per the comment by Tratcher, use app.UseAuthentication(); before app.UseMvc();.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.