I am testing with windows authentication and a local express DB. My DB has users and roles tables.
Following link explains this concept:
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[Authorize(Roles = "Managers")]
public ActionResult CompanySecrets()
{
return View();
}
[Authorize(Users="redmond\\\\swalther")]
public ActionResult StephenSecrets()
{
return View();
}
}
Above roles are coming from NTLM. Is there a way where i can map roles in my DB table so that these are then available to me like User.IsInRoles(“Admin”) etc?
Basically, i want to do some thing like below. Please note that this is webforms code using forms authentication. I would like to change it to use for my tutorial.
Global.asax
-----------
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
Session.Abandon();
FormsAuthentication.SignOut();
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id =
(FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
// Get the stored user-data, in this case, our roles
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
}
}
}
}
Login Process - Sign In Class
----------------------
public HttpCookie SignIn(Person objPerson)
{
// Initialize FormsAuthentication
FormsAuthentication.Initialize();
// Create a new ticket used for authentication
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
objPerson.PersonID.ToString(), // Username associated with ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddMinutes(360), // Date/time to expire
true, // "true" for a persistent user cookie
objPerson.SignIn.RolesListForAuthentication, // User-data, in this case the roles, this is used by the global.asa
FormsAuthentication.FormsCookiePath);// Path cookie valid for
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
// Set the cookie's expiration time to the tickets expiration time
//if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
return cookie;
// Add the cookie to the list for outgoing response
//Response.Cookies.Add(cookie);
}
Login Process
-------------
//create object to the sign in class
ACWebUserSignIn mySignIn = new ACWebUserSignIn();
//Sign in the user, it will return a cookie
HttpCookie myCookie = mySignIn.SignIn(objPerson);
Response.Cookies.Add(myCookie);