简体   繁体   中英

Authorize Admin Controller in ASP.Net MVC 4

I am building a website using mvc4 and c#. I have an admin controller. I want to authenticate that controller.

I have an SQL db table user (that contain User_NA,User_pwd, and User_role) based on the role how can I login to admin index page.

[Authorize]   
public ActionResult Index(string id="")
{
     ViewBag.Admin = id;
     return View();
}

I have a Login and Logout Actions.

[HttpGet]
public ViewResult Login()
{
    return View();
}
[HttpPost]
public RedirectResult Login(FormCollection form)
{
    string uid = Request.Form["userid"];
    string pwd = Request.Form["password"];
    ...............................
    else return Redirect("~/Admin/Login");
}

public RedirectResult Logout()
{
    System.Web.Security.FormsAuthentication.SignOut();
    return Redirect("~/Admin");
}

How can I write the authentication code into login action? And is there any change in Web.Config file or any other files?

you can use WebSecuriy.Login Method

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, 
          model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(returnUrl);
}

// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}

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