I'm developing an application using ASP.Net Core MVC 3.1 and i am facing a problem where it fails to sign-in. localhost response 401 unauthorized
AccountController
[HttpPost]
public async Task<IActionResult> Login(PixClient client)
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Email, client.Email));
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(principal));
return RedirectToAction("Index", "Home");
}
Startup.cs
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
options.LoginPath = "/account/login";
options.Cookie.Name = "sessionid";
});
Index.cs
[Authorize]
public IActionResult Index()
{ ...
CodePudding user response:
I checked the codes you've shown,there's no mistake in it. Make sure you've added the Authentication middleware and it was in correct order:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.......
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
......
}
And you could create a middleware to check if the ticked is generated and added to cookie successfully:
app.Use(async (context, next) =>
{
var cookies = context.Request.Cookies;
await next.Invoke();
});
I tried as below:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie( m =>
{
m.LoginPath = new Microsoft.AspNetCore.Http.PathString("/Home/Login");
m.Cookie.Name = "CookieAuth";
});
When redirect to /Home/Login
,you could see the cookie namedCookieAuth
: