第五章 權限驗證

源代碼GitHub:https://github.com/ZhaoRd/Zrd_0001_AuthorityManagementhtml

1.介紹

        權限驗證過程當中,如何判斷全部過程是一個難點,少判斷一個過程,那麼這個驗證就不完整。git

       本節主要介紹了在這個Demo中使用的驗證原理以及過程github

2.驗證原理

        在上一章中說道驗證過程主要是依賴mvc的controller和action,經過attribute採集信息。c#

        在mvc中,添加IAuthorizationFilter接口的實現類,實現OnAuthorization方法,全部的權限驗證均在這個方法內完成,在FilterConfig類中註冊該實現,代碼以下:5b85431b-8086-4409-9474-b09e753fbb3c架構

        咱們經過判斷AllowAnonymousAttribute是否是匿名訪問,經過判斷SystemModelAttribute是否是系統模塊,經過判斷NeedLoginedAttribute是否是須要登陸訪問,經過判斷PermissionSettingAttribute是否是具備權限限制。mvc

3.驗證過程

1. 匿名訪問

a43dd9d6-1b7f-4c55-be65-44a03c5089a4

2. 非系統模塊

d9a522c0-1667-49d5-a19e-4bc095adfca8

3. 須要登陸訪問,用戶未登陸這返回HttpUnauthorizedResult

51470c23-f74e-4903-93f3-815e6029c1c8

4. 用戶已登陸,可是action是沒有權限限制的,也經過

9705191f-d18c-49dc-910e-cd2396fd01b2

5. 判斷權限

dbaf19f3-0a71-46b7-a527-90849712b51b

4.代碼

 

namespace AuthorityManagement.Web.Filters
{
    using System;
    using System.Text;
    using System.Web.Mvc;
    using System.Web.Security;

    using Presentation.Attributes;
    using Presentations;
    using Presentations.Attributes;

    using Skymate;
    using Skymate.Engines;

    using AllowAnonymousAttribute = System.Web.Http.AllowAnonymousAttribute;

    /// <summary>
    /// The my authorization filter.
    /// </summary>
    public class MyAuthorizationFilter : IAuthorizationFilter
    {
        /// <summary>
        /// The on authorization.
        /// </summary>
        /// <param name="filterContext">
        /// The filter context.
        /// </param>
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var actionDescriptor = filterContext.ActionDescriptor;
            var controllerDescriptor = filterContext.ActionDescriptor.ControllerDescriptor;

            // 匿名一概綠燈通行
            var isAllowAnonymou = actionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), false);
            if (isAllowAnonymou)
            {
                return;
            }

            // 非系統模塊,一概通行
            var isSystemModel = controllerDescriptor.IsDefined(typeof(SystemModelAttribute), false);
            if (!isSystemModel)
            {
                return;
            }

            // 須要登陸訪問
            var isNeedLogined = actionDescriptor.IsDefined(typeof(NeedLoginedAttribute), false)
                                || controllerDescriptor.IsDefined(typeof(NeedLoginedAttribute), false);

            var userId = string.Empty;
            if (isNeedLogined)
            {
                var authCookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authCookie == null)
                {
                    filterContext.Result = new HttpUnauthorizedResult();
                    return;
                }

                var authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                if (authTicket == null || authTicket.UserData == string.Empty)
                {
                    filterContext.Result = new HttpUnauthorizedResult();
                    return;
                }

                userId = authTicket.UserData;
            }

            var isSetPermission = actionDescriptor.IsDefined(typeof(PermissionSettingAttribute), false);

            // 若是沒有設置具體權限,一概經過
            if (!isSetPermission)
            {
                return;
            }

            var systemModelAttribute = (SystemModelAttribute)controllerDescriptor.GetCustomAttributes(typeof(SystemModelAttribute), false)[0];
            var permissionSetting =
                (PermissionSettingAttribute)
                actionDescriptor.GetCustomAttributes(typeof(PermissionSettingAttribute), false)[0];

            var datatokens = filterContext.RequestContext.RouteData.DataTokens["area"];

            // 計算area
            var areaName = datatokens == null ? string.Empty : datatokens.ToString();

            var groupName = systemModelAttribute.GroupName ?? areaName;

            var permissionService = EngineContext.Current.Resolve<IPermissionService>();

            var isAllowed = permissionService.VerifyAuthority(new VerifyAuthorityInputDto()
                                                                  {
                                                                      LoginUserId = Guid.Parse(userId),
                                                                      GroupName = groupName,
                                                                      PermissionValue = permissionSetting.PermissionValue,
                                                                      SystemModelName = systemModelAttribute.Name
                                                                  });

            if (!isAllowed && filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult
                                           {
                                               Data = OperationResult.Error("無操做權限"),
                                               ContentEncoding = Encoding.UTF8,
                                               JsonRequestBehavior = JsonRequestBehavior.AllowGet
                                           };
                return;
            }

            if (!isAllowed)
            {
                filterContext.HttpContext.Response.Redirect("~/401.html");
            }
        }
    }
}

 

  

 

推薦QQ羣:ui

278252889(AngularJS中文社區)spa

5008599(MVC EF交流羣)架構設計

134710707(ABP架構設計交流羣 )設計

59557329(c#基地 )

230516560(.NET DDD基地 )

本人聯繫方式:QQ:351157970

相關文章
相關標籤/搜索