I am trying to create a login screen using owin on Asp MVC. This is the code that is in the controller.
I have even tried hard coding the values but I still get a 401 when I try enter the dashboard after login.
[HttpPost]
public ActionResult Login(string username, string password)
{
int userId = 0;
string role = string.Empty;
if (new UserManager().IsValid(username, password, ref userId, ref role))
{
var ident = new ClaimsIdentity(
new[] {
// adding following 2 claim just for supporting default antiforgery provider
new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
new Claim(ClaimTypes.Name,username),
// optionally you could add roles if any
new Claim(ClaimTypes.Role, role)
},
DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return RedirectToAction("Dashboard"); // auth succeed
}
// invalid username or password
ModelState.AddModelError("", "invalid username or password");
return View("Index", "_LayoutUnAuthorised");
}
[Authorize(Roles = "Default")]
public ActionResult Dashboard()
{
return View();
}
My startup file is empty am I missing something here
public class Startup
{
public void Configuration(IAppBuilder app)
{
}
}
Understanding Application Sign in Cookie flow Automatically redirect an unauthorized response to the login page. Set the logged in user principal to HttpContext. User, so the rest of ASP.NET pipeline will know what user is authenticated. The following is a basic flow of application forms authentication.
OWIN is an interface between . NET web applications and web server. The main goal of the OWIN interface is to decouple the server and the applications. It acts as middleware. ASP.NET MVC, ASP.NET applications using middleware can interoperate with OWIN-based applications, servers, and middleware.
Yes, you missed the Owin Cookie Configuration on Startup class:
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/Account/LogOn"),
});
}
Install Nuget Package Microsoft.Owin.Security.Cookies
then you are good to go
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