asp.net權限認證:Forms認證


寫在前面

閑着也是閑着,特地總結一些關於.net下的權限認證的方法。

這個系列的文章有很多地方都有借鑒圓中其他博友和互聯網資源的引用,

所以並不是100%原創,歡迎大家吐槽、輕拍。。

 

Forms認證示意圖

Forms認證即是表單認證,需提供身份id和密碼password的進行認證和授權管理。

應該是大家比較熟悉的一種,剛接觸.net可能都會學學這個東西。

下面看看他的工作方式:

 

看圖太乏味,我准備了一個demo

  

 

因為默認首頁為:IndexController/Index,這個頁面只要一行字 “Index”,

效果圖:

OK,頁面沒有做任何權限控制,顯示正常。

 

接下來看看DefaultController/Index

using System.Web.Mvc;

namespace Forms.Controllers
{
    public class DefaultController : Controller
    {
        [Authorize]
        public ActionResult Index()
        {
            return View();
        }
    }
}

  

訪問:http://localhost:12463/default

很明顯 沒有權限查看,因為我們設置了權限認證

[Authorize]
public ActionResult Index()

 

設置登錄地址

一般情況下生產環境不會允許直接顯示這種401的錯誤

如果用戶沒有登錄憑證,我們會要求用戶返回登錄頁面完成認證操作,

Forms認證支持在web.config里邊設置登錄地址

 

好了,我們再試試:http://localhost:12463/default

如期跳轉至認證頁面!點擊login,認證成功的話會跳回 http://localhost:12463/default

我們看看login對應的后台處理邏輯

        public ActionResult Index()
        {
            var returnUrl = Request["ReturnUrl"];

            if (Request.HttpMethod == "POST")
            {
                var userid = Request["userid"];
                var password = Request["password"];

                if (userid == "123456" && password == "123456")
                {
                    var ticket = new FormsAuthenticationTicket(
                        1,
                        userid,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(20),
                        true,
                        "role1,role2,role3",
                        "/"
                    );

                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                    cookie.HttpOnly = true;
                    HttpContext.Response.Cookies.Add(cookie);

                    return Redirect(returnUrl);
                }
            }

            ViewBag.ReturnUrl = returnUrl;

            return View();
        }

  

  

 

好了,如願顯示!至此,簡單權限認證完成了。

 

添加角色功能

前邊只是做了簡單的登錄認證,如果項目要求權限的認證粒度比較細的話,就不能滿足了。

比如:IndexNeedRole4只對某role4開放

[MyAuthorize(Roles = "role4")]
public ActionResult IndexNeedRole4()
{
    return View();
}

 

我們需要新建用於驗證角色和用戶名的Authorize特性:MyAuthorize

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
            var ticket = FormsAuthentication.Decrypt(cookie.Value);
            var roles = ticket.UserData;

            var inRoles = false;
            foreach (var role in roles.Split(','))
            {
                if (Roles.Contains(role))
                {
                    inRoles = true;
                    break;
                }
            }

            return inRoles;
        }
    }

  

代碼加好了,我們再試試:http://localhost:12463/default/IndexNeedRole4

返回正常,回到了權限認證界面。

點擊 login,發現這個頁面只是刷新了,所有input都清空了

這是正常的,因為在login/index里邊登錄邏輯的ticket角色只賦值了"role1,role2,role3"

加上role4

        public ActionResult Index()
        {
            var returnUrl = Request["ReturnUrl"];

            if (Request.HttpMethod == "POST")
            {
                var userid = Request["userid"];
                var password = Request["password"];

                if (userid == "123456" && password == "123456")
                {
                    var ticket = new FormsAuthenticationTicket(
                        1,
                        userid,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(20),
                        true,
                        "role1,role2,role3,role4",
                        "/"
                    );

                    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                    cookie.HttpOnly = true;
                    HttpContext.Response.Cookies.Add(cookie);

                    return Redirect(returnUrl);
                }
            }

            ViewBag.ReturnUrl = returnUrl;

            return View();
        }

  

再次點擊login

OK, 如期顯示正常

 

asp.net權限認證系列

  1. asp.net權限認證:Forms認證
  2. asp.net權限認證:HTTP基本認證(http basic)
  3. asp.net權限認證:Windows認證
  4. asp.net權限認證:摘要認證(digest authentication)
  5. asp.net權限認證:OWIN實現OAuth 2.0 之客戶端模式(Client Credential)
  6. asp.net權限認證:OWIN實現OAuth 2.0 之密碼模式(Resource Owner Password Credential)
  7. asp.net權限認證:OWIN實現OAuth 2.0 之授權碼模式(Authorization Code)
  8. asp.net權限認證:OWIN實現OAuth 2.0 之簡化模式(Implicit)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM