MVC 使用者權限HttpContext.User.IsInRole()

來源:互聯網
上載者:User

標籤:val   else   icp   name   isnull   span   ipa   copy   models   

這幾天在用MVC做一個項目,用到了HttpContext.User.IsInRole() 這個方法,但是每次當我用的時候,HttpContext.User.IsInRole(“Admin”) 返回的永遠是false。 在網上查了很多資料,發現都沒有解決,要解決的話,也要實現一系列的擴充方法。好,廢話少說,正式進入主題:

許可權判斷

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
{
  …….
}

上面的代碼中HttpContext.User.IsInRole(“Admin”) 返回的是false。我們要返回True怎麼辦?

在Global.asax中添加以下方法:

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

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

添加好以後,進入你的登入頁面,給目前使用者授權。請看:

LogOn

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

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

 好了,直到這裡,所有的問題,已經解決了。如果大家有其他的好的方法,可以分享, 歡迎留言指正 :)

MVC 使用者權限HttpContext.User.IsInRole()

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.