I am trying to make authorize by using web.config.
In my user registration, it is not using ASP.NET Configuration.
I am handling the login page with database.
I want to protect admin page as manual typing in address from other people.
I put this code in Web.config.
//Web.config
<location path="Product">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
When admin log in website from homepage which has partial logon page,
It will get userName and admin whether is false or true through database.
[HttpPost]
public ActionResult Index(Customer model)
{
if (ModelState.IsValid)
{
//define user whether admin or customer
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["rentalDB"].ToString());
String find_admin_query = "SELECT admin FROM Customer WHERE userName = '" + model.userName + "' AND admin ='true'";
SqlCommand cmd = new SqlCommand(find_admin_query, conn);
conn.Open();
SqlDataReader sdr = cmd.ExecuteReader();
//it defines admin which is true or false
model.admin = sdr.HasRows;
conn.Close();
//if admin is logged in
if (model.admin == true) {
if (DAL.UserIsVaild(model.userName, model.password))
{
FormsAuthentication.SetAuthCookie(model.userName, true);
return RedirectToAction("Index", "Product");
}
}
//if customer is logged in
if (model.admin == false) {
if (DAL.UserIsVaild(model.userName, model.password))
{
FormsAuthentication.SetAuthCookie(model.userName, true);
return RedirectToAction("Index", "Home");
}
}
ModelState.AddModelError("", "The user name or password is incorrect.");
}
// If we got this far, something failed, redisplay form
return View(model);
}
Then my question is, how can I define the user by web.config instead of “*”, like using model.userName or model.admin? Could you tell me how to define the users? thanks.
Firstly, you cannot use the
authorizationelement in the web.config to protect paths like you can for ASP.NET WebForms. This is because the routes in MVC are not physical paths like in WebForms.Secondly, you may wish to roll your own
MembershipProviderandRoleProvider, as it will integrate nicely with ASP.NET and MVC. it’s pretty trivial, and you can substitute your own DAL to fulfill the provider contracts.Here’s what your controllers might look like once you’ve implemented your own providers:
If you don’t want to make your own providers, there are two other options to get the same functionality as the
[Authorization]decorations:Subscribe to the
AuthenticateRequestevent in your global.asax.cs, check to make sure theUser.Identity.IsAuthenticatedproperty is true (which it will be able to tell you from the forms auth ticket will have been processed for you at this point). If it is true, load your roles from your DAL and create a new membership object, adding in the roles you found from the DAL. Now you can useAuthorizeAttributeanywhere else.Create your own derivative
AuthorizeAttributethat uses your DAL to get the user’s roles.