MVC User Rights HttpContext.User.IsInRole ()

Source: Internet
Author: User

These days, using MVC to do a project, the use of HttpContext.User.IsInRole () this method, but every time when I use, HttpContext.User.IsInRole ("Admin") return is always false. In the online search a lot of information, found that there is no solution, to solve the words, but also to implement a series of extension methods. Okay, cut the crap and formally enter the topic:

Authority judgment

if (HttpContext.User.Identity = = NULL | | String.IsNullOrEmpty (HttpContext.User.Identity.Name))
{
Return Redirect ("~/account/logon?returnurl=/service");
}
else if (HttpContext.User.IsInRole ("Admin"))
{
Return redirecttoaction ("Index", "Adminservice");
}
Else
{
.......
}

if (HttpContext.User.Identity = = NULL | | String.IsNullOrEmpty (HttpContext.User.Identity.Name))
{
Return Redirect ("~/account/logon?returnurl=/service");
}
else if (HttpContext.User.IsInRole ("Admin"))
{
Return redirecttoaction ("Index", "Adminservice");
}
Else
{
.......
}

The HttpContext.User.IsInRole ("Admin") returned in the above code is false. What do we do to return true?

In Global.asax, Add the following methods:

<summary>
Authen Right for user
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>

Assigning permissions to login users
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)
{
Get Current User identitied by forms
FormsIdentity id = (formsidentity) HttpContext.Current.User.Identity;
Get FormsAuthenticationTicket Object
FormsAuthenticationTicket ticket = ID. Ticket;
String userData = Ticket. UserData;
string[] roles = Userdata.split (', ');
Set the new identity for current user.
HttpContext.Current.User = new GenericPrincipal (ID, roles);
}
}
}
}

<summary>
Authen Right for user
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
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)
{
Get Current User identitied by forms
FormsIdentity id = (formsidentity) HttpContext.Current.User.Identity;
Get FormsAuthenticationTicket Object
FormsAuthenticationTicket ticket = ID. Ticket;
String userData = Ticket. UserData;
string[] roles = Userdata.split (', ');
Set the new identity for current user.
HttpContext.Current.User = new GenericPrincipal (ID, roles);
}
}
}
}

Once added, go to your login page and authorize the current user. Please see:

LogOn

[HttpPost]
Public ActionResult LogOn (Logonmodel model, string returnUrl)
{
if (modelstate.isvalid)
{
if (ValidateUser (model. UserName, model. Password)))
{

Assign permission to login successful user
UserInfo UserInfo = GetUserInfo (model. UserName);
if (Userinfo.role = = "Admin") {
role = "Admin";
}
FormsAuthenticationTicket AuthTicket = new FormsAuthenticationTicket (1,
Userinfo.alias,
DateTime.Now,
DateTime.Now.AddMinutes (30),
False
role);
String encticket = Formsauthentication.encrypt (AuthTicket);
This. RESPONSE.COOKIES.ADD (New HttpCookie (Formsauthentication.formscookiename,encticket));

Formsauthentication.setauthcookie (model. UserName, model. RememberMe);
if (Url.islocalurl (RETURNURL) && returnurl.length > 1 && returnurl.startswith ("/")
&&!returnurl.startswith ("//") &&!returnurl.startswith ("/\\"))
{
Return Redirect (RETURNURL);
}
Else
{
Return redirecttoaction ("Index", "Home");
}
}
Else
{
Modelstate.addmodelerror ("", "the user name or password provided is incorrect.");
}
}

If we got this far, something failed, redisplay form
return View (model);
}

[HttpPost]
Public ActionResult LogOn (Logonmodel model, string returnUrl)
{
if (modelstate.isvalid)
{
if (ValidateUser (model. UserName, model. Password)))
{
UserInfo UserInfo = GetUserInfo (model. UserName);
if (Userinfo.role = = "Admin") {
role = "Admin";
}
FormsAuthenticationTicket AuthTicket = new FormsAuthenticationTicket (1,
Userinfo.alias,
DateTime.Now,
DateTime.Now.AddMinutes (30),
False
role);
String encticket = Formsauthentication.encrypt (AuthTicket);
This. RESPONSE.COOKIES.ADD (New HttpCookie (Formsauthentication.formscookiename,encticket));

Formsauthentication.setauthcookie (model. UserName, model. RememberMe);
if (Url.islocalurl (RETURNURL) && returnurl.length > 1 && returnurl.startswith ("/")
&&!returnurl.startswith ("//") &&!returnurl.startswith ("/\\"))
{
Return Redirect (RETURNURL);
}
Else
{
Return redirecttoaction ("Index", "Home");
}
}
Else
{
Modelstate.addmodelerror ("", "the user name or password provided is incorrect.");
}
}

If we got this far, something failed, redisplay form
return View (model);
}

Well, until here, all the problems have been solved. If you have other good ways to share, welcome to the message:)

MVC User Rights HttpContext.User.IsInRole ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.