溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

MVC3----應(yīng)用程序的安全性(1)之Authorize

發(fā)布時(shí)間:2020-06-28 12:43:51 來源:網(wǎng)絡(luò) 閱讀:700 作者:1473348968 欄目:編程語言

 

一、如何禁止匿名訪問


1,配置Web.config文件

    <authentication mode="Forms">
      <forms loginUrl="~/Account/ZhangDi" timeout="2880" />
    </authentication>

2,控制器代碼

①:阻止匿名訪問:

         [Authorize]
        public ActionResult Edit(int id)
        {
            PersonError person = db.PersonErrors.Single(r => r.STU_ID == id);
            return View(person);
        }

 ②:還可以阻止匿名訪問整個(gè)控制器:

        [Authorize]

        public class PersonErrorController : Controller
        {

        }

③:創(chuàng)建一個(gè)身份驗(yàn)證票證(有了這個(gè)就可以訪問頁面了)

        returnUrl:返回的路徑

        [HttpPost]
        public ActionResult ZhangDi(string txtname, string returnUrl)
        {

            //第二個(gè)參數(shù)為true會記住密碼

            FormsAuthentication.SetAuthCookie(txtname, false);

            //判斷是否是有效的路徑

            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("http://") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }

        }

④:獲取用戶名稱

            //是否驗(yàn)證了用戶
            if(User.Identity.IsAuthenticated)
            {
                //獲取用戶名稱
                string username = User.Identity.Name;
            }

 ⑤:刪除身份驗(yàn)證票證

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

 

 

 

二、對特定角色訪問權(quán)限控制


 1,配置Web.config文件

    <authentication mode="Forms">
      <forms loginUrl="~/Account/ZhangDi" timeout="2880" />
    </authentication>

 

2,多種授權(quán)方式

①:對多個(gè)角色授權(quán)訪問:

[Authorize(Roles="admin,superadmin")]

public class PersonErrorController : Controller
{

}

②:對多個(gè)用戶授權(quán)訪問:

[Authorize(Users="test1,test2")]

public class PersonErrorController : Controller
{

}

③:同時(shí)授權(quán)給用戶和角色

[Authorize(Roles="admin,user",Users="test1,test2")]

public class PersonErrorController : Controller
{

}

 

3,控制器代碼

①:在Global.asax配置Application_AuthenticateRequest事件(當(dāng)安全模塊已建立用戶標(biāo)識時(shí)發(fā)生

        protected void Application_AuthenticateRequest()
        {
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        FormsIdentity userident = (FormsIdentity)HttpContext.Current.User.Identity;
                        string UserData = userident.Ticket.UserData;
                        string[] roles = UserData.Split(',');
                        //設(shè)置用戶角色
                        HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(userident, roles);
                    }
                }
            }
        }

 

 

②:創(chuàng)建一個(gè)身份驗(yàn)證票證

        [HttpPost]
        public ActionResult ZhangDi(string txtname, string returnUrl)
        {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                1,//票證的版本號
                txtname,//用戶名 
                DateTime.Now,//票證發(fā)出的時(shí)間
                DateTime.Now.AddHours(1),//票證過期時(shí)間
                false , //是否將票證持久存儲在cookie中(和記住密碼沒關(guān)系)
                "admin");//角色
            //加密驗(yàn)證票證
            string ticketEncrypt = FormsAuthentication.Encrypt(ticket);
            //實(shí)例化cookie
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketEncrypt);
            
            //記住密碼
            cookie.Expires = DateTime.MaxValue;
            cookie.Path = "/";
            //將cookie添加到cookie集中
            Response.Cookies.Add(cookie);
            return Redirect(returnUrl);
        }

 

③:獲取用戶名稱

//是否驗(yàn)證了用戶
if(User.Identity.IsAuthenticated)
{
//獲取用戶名稱
string username = User.Identity.Name;
}

④:刪除身份驗(yàn)證票證

public ActionResult LogOff()
{
FormsAuthentication.SignOut();

return RedirectToAction("Index", "Home");
}

 

 

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI