简体   繁体   中英

MVC 3 location allow users in web.config

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.

From your question I'm not entirely sure what you want to do. It sounds like you have a custom authentication system but you still want to use Forms Authentication? That sounds a little messy. I wouldn't recommend two authentication systems on the same site. You could write a custom membership provider but then you wouldn't define users in your web.config.

In response to the last part of your question you can define users in your web.config as follows:

<authentication mode="Forms">
<forms loginUrl="Logon.aspx" defaultUrl="Default.aspx">
<credentials passwordFormat="Clear">
<user name="user" password="pass" />
</credentials>
</forms>
</authentication>

To use the above user in MVC you would then add the [Authorize] attribute to your controller as follows:

[Authorize]
public ActionResult Index(Customer model)
{
}

The above requires the user to already be authenticate. If not the user will be redirected to the loginUrl specified in the web.config. Not sure this will work in your situation as it sounds like you want all users to access your Index action.

Firstly, you cannot use the authorization element 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 MembershipProvider and RoleProvider , 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:

public class AuthController : Controller
{
    public ActionResult Index(Customer model)
    {
        if (ModelState.IsValid)
        {
            if (Membership.ValidateUser(model.userName, model.password))
            {
                if (Roles.IsUserInRole(model.userName, "admin")) return RedirectToAction("Index", "Product");

                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); 
    }
}

[Authorize(Roles = "user")]
public class HomeController : Controller
{

    public ActionResult Index()
    {
        return View();
    }
}

[Authorize(Roles = "admin")]
public class ProductController : Controller
{

    public ActionResult Index()
    {
        return View();
    }
}

If you don't want to make your own providers, there are two other options to get the same functionality as the [Authorization] decorations:

  1. Subscribe to the AuthenticateRequest event in your global.asax.cs, check to make sure the User.Identity.IsAuthenticated property 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 use AuthorizeAttribute anywhere else.

  2. Create your own derivative AuthorizeAttribute that uses your DAL to get the user's roles.

You probably do not want to define each user individually, use roles instead. Then you can specify which roles can perform which operation by using Authorize attribute or in your custom Authorization Filter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM