Apps.Models.PermissionModel LoadMenuBtns(System.Web.Mvc.AuthorizationContext filterContext) { string strCurAreaName = null; if (filterContext.RouteData.DataTokens.ContainsKey("area")) { strCurAreaName = filterContext.RouteData.DataTokens["area"].ToString().ToLower(); } string strControllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; string strActionName = filterContext.ActionDescriptor.ActionName; Apps.Models.PermissionModel curPer = opeCur.GetUsrPermission(strCurAreaName, strControllerName, strActionName, opeCur.Request.HttpMethod); if (curPer != null) { var sonBtns = opeCur.UsrNowPers.Where(o => o.ParentId == curPer.Id && o.OperationType == 3).OrderBy(o => o.Sort).ToList(); //if (sonBtns.Count==0) { if (curPer.OperationType == 3) { sonBtns.Add(curPer); //} filterContext.Controller.ViewBag.sonBtns = sonBtns; //filterContext.Controller.ViewBag.sonBtns = emptyBtns; } else { filterContext.Controller.ViewBag.sonBtns = sonBtns; } return(curPer); } else { filterContext.Controller.ViewBag.sonBtns = emptyBtns; return(curPer); } }
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { //HttpRequest request = HttpContext.Current.Request; //string userName = request["username"]; //HttpCookie cookie = request.Cookies["__sid"]; //if (cookie != null && !string.IsNullOrEmpty(cookie.Value)) //{ // Hashtable aHT = Authorizes.GetAuthorizeCache(cookie.Value); // if (aHT != null) // { // FormsAuthenticationTicket authTicket = aHT["ticket"] as FormsAuthenticationTicket; // if (authTicket != null) // { // if (authTicket.UserData == request.UserHostAddress) // { // if (userName == ParamUtil.Pick(aHT).GetValueAsString("DOMAINUSER")) // { // // 检验成功,跳出方法 // return; // } // } // ACachTool.PickCachTool().SetValue(authTicket.Name, null); // } // } // ACachTool.PickCachTool().SetValue(cookie.Value, null); //} //// 如果验证失败,则跳到首页 //filterContext.Result = new RedirectResult("/"); //request.Cookies.Remove("__sid"); }
/// <summary> /// 区域黑名单 /// </summary> //List<string> blackAreaNames = new List<string>() { "admin" }; public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { string strCurAreaName = null; if (filterContext.RouteData.DataTokens.ContainsKey("area")) { strCurAreaName = filterContext.RouteData.DataTokens["area"].ToString().ToLower(); } if (!IsDefind <Apps.Common.Attrs.SkipLoginAttribute>(filterContext)) { if (IsLogin()) { Apps.Models.PermissionModel curPer = LoadMenuBtns(filterContext); if (!IsDefind <Apps.Common.Attrs.SkipPermissionAttribute>(filterContext)) { if (curPer == null) { filterContext.Result = SendMsg(AjaxMsgStatu.NoPermission, "您没有进行此项操作的权限"); } } } else { filterContext.Result = SendMsg(AjaxMsgStatu.NoLogin, "您尚未登录", "/Account/Index"); } } }
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { ////string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; ////string actionName = filterContext.ActionDescriptor.ActionName; ////implement to retrieve role base on Activity //string roles = "User";//GetRoles.GetActionRoles(actionName, controllerName); //if (!string.IsNullOrWhiteSpace(roles)) //{ // this.Roles = roles;//roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); //} if (!string.IsNullOrEmpty(Operations)) { ApplicationDbContext db = new ApplicationDbContext(); var operationList = this.Operations.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); var roles = (from rp in db.RoleOperations join r in db.Roles on rp.RoleId equals r.Id where operationList.Contains(rp.OperationId) select r.Name).ToList(); Roles = string.Join(",", roles); } //Roles = Roles + (string.IsNullOrEmpty(Roles)?"":",") + "SuperAdmin"; base.OnAuthorization(filterContext); }
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext) { var returnUrl = filterContext.HttpContext.Request.Url.AbsoluteUri; var loginUrl = System.Web.Security.FormsAuthentication.LoginUrl; filterContext.HttpContext.Response.Redirect(loginUrl + "?returnUrl=" + HttpUtility.UrlEncode(returnUrl)); }
private void LoadMenuBtns(System.Web.Mvc.AuthorizationContext filterContext) { //获取当前请求url数据 string strCurAreaName = filterContext.RouteData.DataTokens["area"].ToString().ToLower(); string strControllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; string strActionName = filterContext.ActionDescriptor.ActionName; EFEntity.Menu menuPer = opeCur.GetUserMenuPermission(strCurAreaName, strControllerName, strActionName, opeCur.Request.HttpMethod); //2如果存在此权限在,则加载用户 在此页面的 按钮集合 if (menuPer != null) { //再根据菜单权限 去 当前登录用户Session的 权限集合中 查找 子按钮权限集合 var sonBtns = opeCur.UserMenus.Where(c => c.FatherID == menuPer.MenuId && c.Type == (int)MenuType.BUTTON && !c.IsDelete.Value).OrderBy(c => c.OrderNo).ToList(); if (sonBtns == null) { filterContext.Controller.ViewBag.sonBtns = emptyBtns; } else { filterContext.Controller.ViewBag.sonBtns = sonBtns; } } else { filterContext.Controller.ViewBag.sonBtns = emptyBtns; } }
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext) { if (filterContext.HttpContext.User.Identity.IsAuthenticated) { string controller = string.Empty; string action = string.Empty; if (filterContext.HttpContext.User.IsInRole(RoleEnum.Advertiser.ToString())) { controller = "Advertiserprofile"; action = "createprofile"; } else if (filterContext.HttpContext.User.IsInRole(RoleEnum.Publisher.ToString())) { controller = "Publisherprofile"; action = "createprofile"; } else { base.HandleUnauthorizedRequest(filterContext); } filterContext.Result = new System.Web.Mvc.RedirectToRouteResult( new System.Web.Routing.RouteValueDictionary( new { controller = controller, action = action }) ); } else { base.HandleUnauthorizedRequest(filterContext); } }
/// <summary> /// 验证方法 - 在 ActionExcuting过滤器之前执行 /// </summary> /// <param name="filterContext"></param> public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { //1.如果请求的 Admin 区域里的 控制器类和方法,那么就要验证权限 if (filterContext.RouteData.DataTokens.Keys.Contains("area") &&//当前请求匹配的 路由对象中 是否 有 area区域 filterContext.RouteData.DataTokens["area"].ToString().ToLower() == "admin") //监测区域名 是否为 admin { //2.检查 被请求的 方法 和 控制器是否有 Skip 标签,如果有,则不验证;如果没有,则验证 if (!filterContext.ActionDescriptor.IsDefined(typeof(Common.Attributes.SkipAttribute), false) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(Common.Attributes.SkipAttribute), false)) { #region 1.验证用户是否登陆(Session && Cookie) //1.验证用户是否登陆(Session && Cookie) if (!OperateContext.Current.IsLogin()) { filterContext.Result = OperateContext.Current.Redirect("/admin/admin/login", filterContext.ActionDescriptor); } #endregion #region //2.验证登陆用户 是否有访问该页面的权限 else { //2.获取 登陆用户权限 string strAreaName = filterContext.RouteData.DataTokens["area"].ToString().ToLower(); string strContrllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower(); string strActionName = filterContext.ActionDescriptor.ActionName.ToLower(); string strHttpMethod = filterContext.HttpContext.Request.HttpMethod; if (!OperateContext.Current.HasPemission(strAreaName, strContrllerName, strActionName, strHttpMethod)) { filterContext.Result = OperateContext.Current.Redirect("/admin/admin/login?msg=noPermission", filterContext.ActionDescriptor); } } #endregion } } }
/// <summary> /// 根据当前访问的页面 查找 登录用户的 子按钮权限 /// </summary> void LoadMenuButtons(System.Web.Mvc.AuthorizationContext filterContext) { //1.获取当前请求url数据 string strCurAreaName = filterContext.RouteData.DataTokens["area"].ToString().ToLower(); string strControllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; string strActionName = filterContext.ActionDescriptor.ActionName; //1.1根据当前访问url找到 登录用户的 菜单权限(到登录用户的Session中存放的权限集合中) Permission menuPermission = operationContext.GetUserPermission(strCurAreaName, strControllerName, strActionName, HttpContext.Current.Request.HttpMethod); //1.2如果存在此权限在,则加载用户 在此页面的 按钮集合 if (menuPermission != null) { //2.再根据菜单权限 去 当前登录用户Session的 权限集合中 查找 子按钮权限集合 var buttons = operationContext.CurrentUserPermissions.Where(o => o.permissionParentID == menuPermission.permissionID && o.permissionOperationType == EnumHelper.OperationType.BUTTON && o.permissionIsDeleted == false).OrderBy(o => o.permissionOrder).ToList(); //4.如果 登录用户 没有任何 该页面的 子按钮权限,就设置一个空的权限集合 if (buttons == null) { filterContext.Controller.ViewBag.toolbarButtons = emptyButtons; } else { //5.存入 ViewBag filterContext.Controller.ViewBag.toolbarButtons = buttons; } } else { filterContext.Controller.ViewBag.toolbarButtons = emptyButtons; } }
bool IsDefind <AttrType>(System.Web.Mvc.AuthorizationContext filterContext) { Type attrTypeObj = typeof(AttrType); return(filterContext.ActionDescriptor.IsDefined(attrTypeObj, false) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(attrTypeObj, false)); }
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { if (RequireSecure && !((Controller)HttpContext.Current.Items["controllerInstance"]).ControllerContext.IsChildAction) { base.OnAuthorization(filterContext); } }
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext) { if (Enabled) { var returnUrl = filterContext.HttpContext.Request.Url.AbsoluteUri; filterContext.HttpContext.Response.Redirect(LoginUrl + "?returnUrl=" + HttpUtility.UrlEncode(returnUrl)); } }
/// <summary> /// 检查 过滤器上下文 中的当前被请求的方法 和 控制器 是否有贴标签 /// </summary> /// <typeparam name="AttrType">要检查的标签类型</typeparam> /// <param name="filterContext">过滤器上下文</param> /// <returns></returns> bool IsDefind <AttrType>(System.Web.Mvc.AuthorizationContext filterContext) { //获取要检查的标签 的 类型对象 Type attrTypeObj = typeof(AttrType); //分别检查 被请求的方法 和 控制器上 是否有贴 指定的标签,如果任意贴了,则返回true return(filterContext.ActionDescriptor.IsDefined(attrTypeObj, false) || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(attrTypeObj, false)); }
/// <summary> /// 是否跳过验证 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filterContext"></param> /// <returns></returns> bool DoesSkip <T>(System.Web.Mvc.AuthorizationContext filterContext) where T : Attribute { if (!filterContext.ActionDescriptor.IsDefined(typeof(T), false) && !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(T), false)) { return(false); } return(true); }
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAuthenticated) { filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden); } else { base.HandleUnauthorizedRequest(filterContext); } }
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAuthenticated) { throw new HttpException(403, "Forbidden"); } else { base.HandleUnauthorizedRequest(filterContext); } }
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; if (filterContext.ActionDescriptor.ActionName == "Login" || filterContext.ActionDescriptor.ActionName == "ForgotPassword") { return; } this.containedARs = this.getContainedRoles(controllerName); authorityJudge(filterContext.RequestContext.HttpContext.Request.Cookies["userName"], filterContext.HttpContext); }
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext) { //var claims = System.Security.Claims.ClaimsPrincipal.Current.Claims.ToList(); if (filterContext.HttpContext.Request.IsAuthenticated) { filterContext.Result = new System.Web.Mvc.HttpStatusCodeResult((int)System.Net.HttpStatusCode.Forbidden); } else { base.HandleUnauthorizedRequest(filterContext); } }
/// <summary> /// Called when a process requests authorization. /// </summary> /// <param name="filterContext">The filter context, which encapsulates information for using <see cref="T:System.Web.Mvc.AuthorizeAttribute" />.</param> public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { ClaimsPrincipal user = filterContext.HttpContext.User as ClaimsPrincipal; if (user != null && user.HasClaim(ClaimType, ClaimValue)) { base.OnAuthorization(filterContext); } else { base.HandleUnauthorizedRequest(filterContext); } }
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext) { if (Role == "Admin") { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "admin", action = "login" })); } else { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "user", action = "login" })); } }
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { base.OnAuthorization(filterContext); if (filterContext.HttpContext.User.Identity.IsAuthenticated) { if (UserClaims.PersonId == 0) { UrlHelper helper = new UrlHelper(filterContext.RequestContext); string url = helper.Action("Unauthorized", "Error", null, filterContext.HttpContext.Request.Url.Scheme); filterContext.Result = new RedirectResult(url); } } }
void SetCultureInfo(System.Web.Mvc.AuthorizationContext filterContext) { var langtype = filterContext.HttpContext.Session["CurrentUICulture"] != null ? filterContext.HttpContext.Session["CurrentUICulture"].ToString() : ""; var lang = "zh-CN"; switch (langtype) { case "1": lang = "zh-CN"; break; case "2": lang = "en-US"; break; default: lang = "zh-CN"; break; } System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lang); }
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = filterContext.ActionDescriptor.ActionName; string roles = GetRoles.GetActionRoles(actionName, controllerName); if (!string.IsNullOrWhiteSpace(roles)) { this.Roles = roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); } else { this.Roles = null; } base.OnAuthorization(filterContext); }
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { var principal = filterContext.HttpContext.User; if (principal == null || !principal.Identity.IsAuthenticated) { filterContext.Result = new ViewResult() { ViewName = "AcsLogin", ViewData = filterContext.Controller.ViewData, TempData = filterContext.Controller.TempData }; return; } base.OnAuthorization(filterContext); }
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { //detect if current url has area name if (filterContext.RouteData.DataTokens.ContainsKey("area")) { //0.2 get current area name string strCurAreaName = filterContext.RouteData.DataTokens["area"].ToString(); // if current area is in the blacklist, then detect permission if (blackAreaNames.Contains(strCurAreaName)) { // if [skiplogin] then skip login check if (!IsDefind <SkipLoginCheckAttribute>(filterContext)) { if (IsLogin()) { filterContext.Controller.ViewBag.CurrentUserName = operationContext.CurrentUser.employeeLoginName; LoadMenuButtons(filterContext); // if [skipPermission] then skip permission check if (!IsDefind <SkipPermissionCheckAttribute>(filterContext)) { //2. check if user has permisison to access current url if (!operationContext.HasPermission(strCurAreaName, filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName, HttpContext.Current.Request.HttpMethod)) { filterContext.Result = SendMessage("sorry, you don't have the permission. please login with other account.", "/Admin/User/Login"); } else { //LoadMenuBtns(filterContext); } } else { //LoadMenuBtns(filterContext); } } else { filterContext.Result = SendMessage("Please login first.", "/Admin/User/Login"); } } } } }
public void MvcAuthorizeAttributeTest() { System.Web.Mvc.AuthorizationContext authContext = MockAuthorizationContext; Open.SPF.Web.Mvc.PermissionAuthorizeAttribute uut = new Open.SPF.Web.Mvc.PermissionAuthorizeAttribute("FirstPermission, ThirdPermission"); uut.OnAuthorization(authContext); Assert.IsNull(authContext.Result); uut = new Open.SPF.Web.Mvc.PermissionAuthorizeAttribute("FirstPermission"); uut.OnAuthorization(authContext); Assert.IsNull(authContext.Result); uut = new Open.SPF.Web.Mvc.PermissionAuthorizeAttribute("BOGUS"); uut.OnAuthorization(authContext); Assert.IsNotNull(authContext.Result); Assert.IsInstanceOfType(authContext.Result, typeof(System.Web.Mvc.RedirectResult)); Assert.AreEqual(Properties.Settings.Default.UmauthorizedRedirectPage, ((System.Web.Mvc.RedirectResult)authContext.Result).Url); }
public bool IsValid(System.Web.Mvc.AuthorizationContext context) { if (!IsEnabled) { return(true); } var controllerName = context.RouteData.Values["controller"].ToString(); var action = context.RouteData.Values["action"].ToString(); var controller = AllowControllers.All.FirstOrDefault(p => p.Name.ToLower() == controllerName.ToLower()); if (controller == null) { return(false); } return(!controller.DisallowActions.Any(p => p.ToLower() == action.ToLower())); }
public override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { #if DEBUG // CHANGE TO YOUR USER MANAGER var userManger = filterContext.HttpContext.GetOwinContext().GetUserManager <ApplicationUser>(); var user = userManger.FindByName("***"); if (user == null) { this.Create(new ApplicationUser { /* ... */ }, "***"); } using (var signInManager = new ApplicationSignInManager(userManger, filterContext.HttpContext.GetOwinContext().Authentication)) signInManager.PasswordSignIn(user.UserName, "***", true, false); return; #endif return(base.OnAuthorization(filterContext)); }
/// <summary> /// Method called when authorization occurs. /// </summary> /// <param name="filterContext">Contains information about the current request and action.</param> protected override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext) { base.OnAuthorization(filterContext); HttpCookie cookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie != null) { User user = SetUserToContext(cookie); if (user == null) { HttpContext.Response.Redirect("~/Login"); } } else { HttpContext.Response.Redirect("~/Login"); } }
protected override void HandleNonHttpsRequest(System.Web.Mvc.AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.Url.Scheme != Uri.UriSchemeHttps) { var request = filterContext.HttpContext.Request; if (request.HttpMethod == "GET") { base.HandleNonHttpsRequest(filterContext); } else { filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = 404; } } else { base.HandleNonHttpsRequest(filterContext); } }