• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Mvc.AuthorizationContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Web.Mvc.AuthorizationContext的典型用法代码示例。如果您正苦于以下问题:C# AuthorizationContext类的具体用法?C# AuthorizationContext怎么用?C# AuthorizationContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



AuthorizationContext类属于System.Web.Mvc命名空间,在下文中一共展示了AuthorizationContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: OnAuthorization

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
                throw new ArgumentNullException("filterContext");
            if (filterContext.IsChildAction)
                return;

            IUser currentUser = UserContext.CurrentUser;
            if (currentUser != null)
            {
                if (currentUser.IsBanned)
                {
                    IAuthenticationService authenticationService = DIContainer.ResolvePerHttpRequest<IAuthenticationService>();
                    authenticationService.SignOut();
                    filterContext.Result = new RedirectResult(SiteUrls.Instance().SystemMessage(filterContext.Controller.TempData, new SystemMessageViewModel
                    {
                        Title = "帐号被封禁!",
                        Body = "由于您的非法操作,您的帐号已被封禁,如有疑问,请联系管理员",
                        StatusMessageType = StatusMessageType.Error
                    }));
                }
                return;
            }
            return;
        }
开发者ID:ClaytonWang,项目名称:Dw3cSNS,代码行数:25,代码来源:IsBannedAttribute.cs


示例2: OnAuthorization

        public virtual void OnAuthorization(AuthorizationContext filterContext) {
            if (filterContext == null) {
                throw new ArgumentNullException("filterContext");
            }

            filterContext.Controller.ValidateRequest = EnableValidation;
        }
开发者ID:sanyaade-mobiledev,项目名称:ASP.NET-Mvc-2,代码行数:7,代码来源:ValidateInputAttribute.cs


示例3: OnAuthorization

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAuthenticated){
                var authorizedUsers = "2,3";
                var authorizedRoles = "Admin";

                Users = String.IsNullOrEmpty(Users) ? authorizedUsers : Users;
                Roles = String.IsNullOrEmpty(Roles) ? authorizedRoles : Roles;

                if (!String.IsNullOrEmpty(Roles)){
                    if (!CurrentUser.IsInRole(Roles)){
                        filterContext.Result = new RedirectToRouteResult(new
                            RouteValueDictionary(new{controller = "Home", action = "AccessDenied"}));

                        // base.OnAuthorization(filterContext); //returns to login url
                    }
                }

                if (!String.IsNullOrEmpty(Users)){
                    if (!Users.Contains(CurrentUser.UserId.ToString())){
                        filterContext.Result =
                            new RedirectToRouteResult(new RouteValueDictionary(new{controller = "Home", action = "AccessDenied"}));

                        // base.OnAuthorization(filterContext); //returns to login url
                    }
                }
            }
            else{
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "Index" }));
            }
        }
开发者ID:Josimar,项目名称:UpperCash,代码行数:31,代码来源:BaseController.cs


示例4: OnAuthorization

        //
        // GET: /Shared/
        protected override void OnAuthorization(AuthorizationContext filterContext)
        {
            var controller=RouteData.Values["controller"];
            string action = RouteData.Values["action"].ToString();
            //var id = Converter.ToInt (Session["ID"],0);
            //APIDataDataContext db = DBFactory.DB;
            //var sg = (from c in db.TAgents
            //          where c.ID == id
            //          select new
            //          {
            //              GroupName = (from d in db.TUserGroup where d.ID == c.GroupID select d.GroupName).FirstOrDefault()
            //          }).FirstOrDefault();
            //if (sg != null)
            //{
            //    var Name = Session["Name"];
            //    var Type = Session["Type"];
            //    ViewData["group"] = sg.GroupName;
                ViewData["controller"] = controller;
                ViewData["action"] = action;
            //}
            //else
            //{
            //    HttpContext.Server.TransferRequest("/login/Land", true);
            //}

            //没登录的话跳转到登录页
            if (Session["ID"] == null)
            {
                //请求页面不是登录页的时候才跳转
                if (action.ToLower() != "land")
                {
                    filterContext.Result = new RedirectResult("/Login/Land");
                }
            }
        }
开发者ID:BriseLee,项目名称:test,代码行数:37,代码来源:SharedController.cs


示例5: HandleUnauthorizedRequest

        protected override void HandleUnauthorizedRequest(AuthorizationContext context)
        {
            if (context.HttpContext.Request.IsAjaxRequest())
            {
                var urlHelper = new UrlHelper(context.RequestContext);
                context.HttpContext.Response.StatusCode = 403;
                context.Result = new JsonResult
                {
                    Data = new
                    {
                        Error = "NoPermission",
                        LogOnUrl = urlHelper.Action("index", "login")
                    },
                    JsonRequestBehavior = JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                context.Result = new RedirectToRouteResult(
                                       new RouteValueDictionary
                                   {
                                       { "action", "index" },

                                       { "controller", "error" },

                                       { "id", (int)ErrorType.NoPermission},

                                       {"returnurl",context.RequestContext.HttpContext.Request.Url}
                                   });
            }
        }
开发者ID:navy235,项目名称:PadCrm,代码行数:31,代码来源:PermissionAuthorizeAttribute.cs


示例6: IsAdminPageRequested

 private bool IsAdminPageRequested(AuthorizationContext filterContext)
 {
     var adminAttributes = GetAdminAuthorizeAttributes(filterContext.ActionDescriptor);
     if (adminAttributes != null && adminAttributes.Any())
         return true;
     return false;
 }
开发者ID:KhangTranIt,项目名称:Bluesky,代码行数:7,代码来源:AdminAuthorizeAttribute.cs


示例7: OnAuthorization

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (filterContext.HttpContext.Request.IsSecureConnection)
            {
                return;
            }

            if (string.Equals(filterContext.HttpContext.Request.Headers["X-Forwarded-Proto"],
                "https",
                StringComparison.InvariantCultureIgnoreCase))
            {
                return;
            }

            if (filterContext.HttpContext.Request.IsLocal)
            {
                return;
            }

            HandleNonHttpsRequest(filterContext);
        }
开发者ID:andyevans2000,项目名称:Illuminate,代码行数:26,代码来源:RequireHttpsAttribute.cs


示例8: OnAuthorization

 public override void OnAuthorization(AuthorizationContext filterContext)
 {
     var actionAttrs = filterContext.ActionDescriptor.GetCustomAttributes(true);
     if (actionAttrs.Any(x => x is AllowAnonymousAttribute))
     {
         return;
     }
     var actionAttr = actionAttrs.FirstOrDefault(x => x is MvcAuthorizeAttribute);
     if (actionAttr != null)
     {
         ((MvcAuthorizeAttribute)actionAttr).Authenticate(filterContext);
         return;
     }
     var controllerAttrs = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(true);
     if (controllerAttrs.Any(x => x is AllowAnonymousAttribute))
     {
         return;
     }
     var controllerAttr = controllerAttrs.FirstOrDefault(x => x is MvcAuthorizeAttribute);
     if (controllerAttr != null)
     {
         ((MvcAuthorizeAttribute)controllerAttr).Authenticate(filterContext);
         return;
     }
     this.Authenticate(filterContext);
 }
开发者ID:yuandong618,项目名称:mvcsolution,代码行数:26,代码来源:MvcAuthorizeAttribute.cs


示例9: OnAuthorization

        public override void OnAuthorization(AuthorizationContext filterContext, IFacebookApplication settings)
        {
            var authorizer = new FacebookWebContext(settings, filterContext.HttpContext);

            if (!string.IsNullOrEmpty(Permissions) && Permissions.IndexOf(" ") != -1)
            {
                throw new ArgumentException("Permissions cannot contain whitespace.");
            }

            long? userId = (null != FacebookWebContext.Current.Session) ? (long?)FacebookWebContext.Current.Session.UserId : null;

            if (null == userId || !AuthorizedUsers.Contains(userId.Value))
            {
                if (!authorizer.IsAuthorized(ToArrayString(Permissions)))
                {
                    this.HandleUnauthorizedRequest(filterContext, FacebookApplication.Current);
                }
                else
                {
                    if (!AuthorizedUsers.Contains(FacebookWebContext.Current.Session.UserId))
                    {
                        AuthorizedUsers.Add(FacebookWebContext.Current.Session.UserId);
                    }
                }
            }
        }
开发者ID:nbclark,项目名称:SportsLink,代码行数:26,代码来源:CanvasAuthorizeAttribute.cs


示例10: OnAuthorization

 public override void OnAuthorization(AuthorizationContext filterContext)
 {
     if (!Common.IsLogedIn())
     {
         filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary {{"Action","Index"},{"Controller","Landing"} });
     }
 }
开发者ID:changtraicantinh,项目名称:testfsoft,代码行数:7,代码来源:LoginRequriedAttribute.cs


示例11: Authenticate

        public void Authenticate(AuthorizationContext filterContext)
        {
            var context = filterContext.RequestContext.HttpContext;
            var isAuthenticated = context.Request.IsAuthenticated;
            if (!string.IsNullOrEmpty(this.Roles))
            {
                isAuthenticated = isAuthenticated && this.Roles.Split(',').Any(r => context.User.IsInRole(r));
            }
            if (isAuthenticated)
            {
                return;
            }

            if (HttpContext.Current.Request["ajax"] == "true")
            {
                filterContext.Result = new StandardJsonResult()
                {
                    Message = context.Request.IsAuthenticated ? "Please login" : "You don't have sufficient permission"
                };
            }
            else
            {
                filterContext.Result = new RedirectResult("/login?returnUrl=" + HttpContext.Current.Request.RawUrl);
            }
        }
开发者ID:yuandong618,项目名称:mvcsolution,代码行数:25,代码来源:MvcAuthorizeAttribute.cs


示例12: OnAuthorization

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                var userId = filterContext.HttpContext.User.Identity.GetUserId();
                var userManager = filterContext.HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
                var currentUser = userManager.FindById(userId);
                if (currentUser.EmailConfirmed == false)
                {

                    //取得 URLHelper
                    var urlHelper = new UrlHelper(filterContext.RequestContext);

                    //將路徑名稱組合
                    var currentControllerAndActionName =
                        string.Concat(filterContext.RouteData.Values["controller"],
                        "_",
                        filterContext.RouteData.Values["action"]);

                    //明確開放[登入][登出][EMAIL驗證]
                    var allowAction = new[] { "Account_Login", "Account_LogOff", "Account_VerifyMail" };

                    if (allowAction.Contains(currentControllerAndActionName) == false)
                    {
                        //所有沒有通過EMAIL驗證的都導向驗證頁面(請視專案需求調整)
                        var redirect = new RedirectResult(urlHelper.Action("VerifyMail", "Account"));
                        filterContext.Result = redirect;
                    }

                }
            }
        }
开发者ID:chimpinano,项目名称:MVC5Book,代码行数:33,代码来源:AuthorizePlusAttribute.cs


示例13: OnAuthorization

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (!String.IsNullOrEmpty(Roles))
                {
                    string[] roleNames = Roles.Split(',');

                    foreach (string role in roleNames)
                    {
                        if (filterContext.HttpContext.User.IsInRole(role))
                        {
                            //base.OnAuthorization(filterContext);
                            base.OnAuthorization(filterContext);
                            return;
                        }
                    }

                    filterContext.Controller.FlashError("You must be assigned one of the following roles" +
                                                        (String.IsNullOrEmpty(Task) ? "" : (" to " + Task)) + ": " +
                                                        Roles);
                    filterContext.Result = new HttpUnauthorizedResult();
                }
                else
                {
                    // all cool. Go on ahead.
                }

            }
            else
                filterContext.Result = new HttpUnauthorizedResult();
        }
开发者ID:pate,项目名称:blog,代码行数:32,代码来源:SiteAuthorizeAttribute.cs


示例14: OnAuthorization

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }

            if (!filterContext.HttpContext.Request.IsSecureConnection)
            {
                if (Redirect)
                {
                    var builder = new UriBuilder(filterContext.HttpContext.Request.Url);

                    builder.Scheme = Uri.UriSchemeHttps;

                    if (Port != 0 && Port != 443)
                    {
                        builder.Port = Port;
                    }

                    filterContext.Result = new RedirectResult(builder.ToString());
                }
                else
                {
                    throw new HttpException((int)HttpStatusCode.Forbidden, "Access forbidden. The requested resource requires an SSL connection.");
                }
            }
        }
开发者ID:pleb,项目名称:Chillow,代码行数:28,代码来源:RequireHttpsAttribute.cs


示例15: OnAuthorization

        /// <summary>
        /// The on authorization act.
        /// </summary>
        /// <param name="filterContext">
        /// The filter context.
        /// </param>
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            // user does not authenticated
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (filterContext.HttpContext.Session != null)
                {
                    filterContext.HttpContext.Session.Add("key", "Please login to view that page.");
                }

                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary
                    {                        
                        { "controller", "Account" },
                        { "action", "Login" },
                        { "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
                    });
                return;
            }

            base.OnAuthorization(filterContext);

            // user already authenticated, but have not permissions to make action
            if (filterContext.Result is HttpUnauthorizedResult)
            {
                filterContext.Result = new RedirectToRouteResult(
                    new RouteValueDictionary
                    {                            
                        { "controller", "Account" },
                        { "action", "PermissionError" },
                        { "ReturnUrl", filterContext.HttpContext.Request.RawUrl }
                    });
            }
        }
开发者ID:nktssh,项目名称:KSS.HorseRasing,代码行数:40,代码来源:KssAuthorize.cs


示例16: OnAuthorization

 public void OnAuthorization(AuthorizationContext filterContext)
 {
     //if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
     //{
     //    filterContext.Result = new RedirectResult("/Account/Login");
     //}
 }
开发者ID:oricalvo,项目名称:course-mvc-rapaport-2015-10,代码行数:7,代码来源:HomeController.cs


示例17: OnAuthorization

        public override void OnAuthorization(AuthorizationContext filterContext)
        {           
            var importer = new WindowsIdentityImporter();
            WindowsIdentityImporter.Import(filterContext);

            if (IsWindowsUserAuthenticated(filterContext))
            {
                return;
            }

            if (filterContext.HttpContext.User == null || !(filterContext.HttpContext.User.Identity is FormsIdentity) || !filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result =
                    new RedirectToRouteResult(new RouteValueDictionary
                    {
                        { "controller", "Home" },
                        { "action", "LogOn" },
                        { "returnUrl", filterContext.HttpContext.Request.Url.PathAndQuery }
                    });
            }
            else
            {
                base.OnAuthorization(filterContext);
                if (filterContext.Result is HttpUnauthorizedResult)
                {
                    filterContext.Result = new RedirectResult("~/Home/Unauthorized");
                }
            }
        }
开发者ID:hammadrauf,项目名称:Bonobo-Git-Server,代码行数:29,代码来源:WebAuthorizeAttribute.cs


示例18: OnAuthorization

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var pre = filterContext.HttpContext.User;

            if (!(pre is DragonPrincipal))
            {
                var ctx = ObjectFactory.GetInstance<DragonContext>();

                if (ctx != null)
                {
                    var permissionStore = ObjectFactory.GetInstance<IPermissionStore>();

                    string[] rights = new string[0];

                    if (permissionStore.HasNode(Guid.Empty))
                    {
                        rights = permissionStore.GetRightsOnNodeWithInherited(Guid.Empty)
                                                    .Where(x => x.SubjectID.Equals(ctx.CurrentUserID))
                                                    .Select(x => x.Spec)
                                                    .ToArray();
                    }

                    filterContext.HttpContext.User = new DragonPrincipal(ctx, rights);
                }
            }
        }
开发者ID:jbinder,项目名称:dragon,代码行数:26,代码来源:DragonIdentityInjector.cs


示例19: OnAuthorization

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null || filterContext.HttpContext == null)
                return;

            HttpRequestBase request = filterContext.HttpContext.Request;
            if (request == null)
                return;

            if (filterContext.IsChildAction)
                return;

            // only redirect for GET requests,
            // otherwise the browser might not propagate the verb and request body correctly.
            if (request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase) == false)
                return;

            if (WebHelper.SslEnabled() == false)
                return;

            var currentConnectionSecured = request.IsSecureConnection;
            if (currentConnectionSecured == false)
            {
                RedirectToSsl(filterContext);
            }
            else
            {
                var secureSsl = _appSettings.SslUrl.Trim();
                if (request.Url.AbsoluteUri.Contains(secureSsl) == false)
                {
                    RedirectToSsl(filterContext);
                }
            }
        }
开发者ID:rickreis,项目名称:safe-environment-asp-net-mvc,代码行数:34,代码来源:RequireSslAttribute.cs


示例20: OnAuthorization

        public virtual void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
                throw new ArgumentNullException("filterContext");

            if (_ignore)
                return;

            //don't apply filter to child methods
            if (filterContext.IsChildAction)
                return;

            //only POST requests
            if (!String.Equals(filterContext.HttpContext.Request.HttpMethod, "POST", StringComparison.OrdinalIgnoreCase))
                return;

            if (!DataSettingsHelper.DatabaseIsInstalled())
                return;
            var securitySettings = EngineContext.Current.Resolve<SecuritySettings>();
            if (!securitySettings.EnableXsrfProtectionForPublicStore)
                return;

            var validator = new ValidateAntiForgeryTokenAttribute();
            validator.OnAuthorization(filterContext);
        }
开发者ID:powareverb,项目名称:grandnode,代码行数:25,代码来源:PublicAntiForgeryAttribute.cs



注:本文中的System.Web.Mvc.AuthorizationContext类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Mvc.ContentResult类代码示例发布时间:2022-05-26
下一篇:
C# Mvc.AreaRegistrationContext类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap