I am just starting to use ASP.Net MVC5 and I am having a little challenge.
I have an already built system that uses WebForms and I am migrating it to MVC.
I understand that MVC provides an Authentication and Authorization provider, but I want to implement a simple login based on the database I already have.
In my previous system, when a user logs in, the id and role of the user is stored in a session variable and checked across all pages. The id is also used for some tasks in the app.
Is there a way to use MVC Identity Management with my existing database?
I tried the following from a previous post but can't seem to get it working.
[HttpPost]
public ActionResult Login(string username, string password)
{
if (new UserManager.IsValid(username, password))
{
var ident = new ClaimsIdentity(
new[] {
// adding following 2 claim just for supporting default antiforgery provider
new Claim(ClaimTypes.NameIdentifier, username),
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, "RoleName"),
new Claim(ClaimTypes.Role, "AnotherRole"),
},
DefaultAuthenticationTypes.ApplicationCookie);
HttpContext.GetOwinContext().Authentication.SignIn(
new AuthenticationProperties { IsPersistent = false }, ident);
return RedirectToAction("MyAction"); // auth succeed
}
// invalid username or password
ModelState.AddModelError("", "invalid username or password");
return View();
}
class UserManager
{
public bool IsValid(string username, string password)
{
using(var db=new MyDbContext()) // use your DbConext
{
// if your users set name is Users
return db.Users.Any(u=>u.Username==username
&& u.Password==password);
}
}
}
Please any help and suggestions will be appreciated.