I am testing the [Authorize] attribute, but I can't make a redirect to login page if the user has not logged yet (the Chrome inspector returns a 401).
This is my code to make the login in my Controller (very simple).
if (model.UserName == "admin" && model.Password == "test")
{
var claims = new[] { new Claim("name", model.UserName), new Claim(ClaimTypes.Role, "Admin") };
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
return RedirectToAction("Index", "Home");
}
And this is my configuration in the Startup.cs for logins:
app.UseCookieAuthentication(options =>
{
options.AutomaticAuthenticate = true;
options.LoginPath = new PathString("/Account/Login");
});
Any ideas?
Thanks!!
Cookie authentication uses HTTP cookies to authenticate client requests and maintain session information. It works as follows: The client sends a login request to the server.
A Cookie-based authentication uses the HTTP cookies to authenticate the client requests and maintain session information on the server over the stateless HTTP protocol. Here is a logical flow of the cookie-based authentication process: The client sends a login request with credentials to the backend server.
SignInAsync(HttpContext, String, ClaimsPrincipal, AuthenticationProperties) Sign in a principal for the specified scheme.
Your Startup.cs should look like the following:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
LoginPath = "/account/login",
AuthenticationScheme = "Cookies",
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
Setting the AutomaticChallenge is what is going to make the [Authorize] attribute work. Be sure to include the [Authorize] attribute on any of the controllers you want the redirect (302) to happen.
There is a very basic sample in this GitHub repo that might provide some guidance: https://github.com/leastprivilege/AspNet5TemplateCookieAuthentication
Try this in the Startup.cs:
app.UseCookieAuthentication(options =>
{
options.AuthenticationType = CookieAuthenticationDefaults.AuthenticationScheme;
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
options.LoginPath = new PathString("/Account/Login");
});
And this in the Controller
IAuthenticationManager authManager = Request.GetOwinContext().Authentication;
authManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With