且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

会话在MVC AuthorizeAttribute中变为空

更新时间:2023-02-26 08:14:01

3年后,我遇到了类似的问题.现在我不是专家,但我相信每个控制器上下文调用在其自己的空间中都是唯一的,因此httpContext.Session在新调用中将为null.

3 years down the line and I ran into a similar issue. Now I'm no expert but I believe each controller context call is unique in it's own space, thus httpContext.Session would be null on a new call.

我的问题是以我想存储(具有其自定义应用程序权限)的登录AD用户的形式出现的.我也在扩展AuthorizationAttribute,但是当将此过滤器应用于控制器操作时,即使用户已保存,httpContext还是为null.

My issue came in the form of a logged in AD user I wanted to store (with his custom application permissions) in a session variable. I'm extending on the AuthorizationAttribute too, but when this filter is applied to a controller action, httpContext is null even though the user was saved.

对于那些遇到相同问题的人们,解决方法是创建一个基本控制器,该用户及其会话状态将在其他所有控制器中保留(继承基本控制器).

For people battling with the same issue, the way around this is to create a base controller where this user and it's session state is kept throughout other controllers (inheriting the base controller).

例如.

我的模特:

public class LoggedInUser
    {
        public somenamespace.userclass UserProfile { get; set; }
        public List<somenamespace.user_permission_class> UserPermissions { get; set; }
    }

我的基本控制器:

public class ControllerBase : Controller
    {
        private LoggedInUser _LoginUser;

        public LoggedInUser LoginUser
        {
            get 
            {
                if (_LoginUser != null)
                    return _LoginUser;

                if (Session["_LoginUser"] == null)
                    return null;

                return Session["_LoginUser"] as LoggedInUser;
            }
            set
            {
                _LoginUser = value;
                Session["_LoginUser"] = _LoginUser;
            }
        }

        public void PerformUserSetup(string sUsername) // sUsername for testing another user, otherwise User.Identity will be used.
        {
            sUsername = string.IsNullOrEmpty(sUsername) ? User.Identity.Name : sUsername;
            sUsername = (sUsername.IndexOf("\\") > 0) ? sUsername.Split('\\').ToArray()[1] : sUsername;

            // Todo - SQL conversion to stored procedure
            List<userclass> tmpUser = Root.Query<userclass>(/*sql to select user*/).ToList();

            List<user_permission_class> tmpUserpermissions = Root.Query<user_permission_class>(/*sql to select user permissions*/).ToList();

            LoggedInUser _LoginUser = new LoggedInUser();
            _LoginUser.UserProfile = tmpUser.First();
            _LoginUser.UserPermissions = tmpUserpermissions;

            LoginUser = _LoginUser;
        }

    }

我的HomeController(任何MVC示例的标准配置):

My HomeController (standard with any MVC example) :

public class HomeController : ControllerBase
    {
        [Authorize] // Standard AuthorizeAttribute (AD test)
        public ActionResult Index()
        {
            if (Session["_LoginUser"] == null)
                PerformUserSetup("");

            return View();
        }
    }

我的自定义"权限检查过滤器,该过滤器将用于其他任何控制器操作:

My Custom permission checking filter which I'll use on any other controller action:

public class PermissionAuthorize : AuthorizeAttribute
    {
        private readonly string[] permissions;
        public PermissionAuthorize(params string[] perms)
        {
            this.permissions = perms;
        }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool auth = false;

            if (httpContext.Session["_LoginUser"] == null)
            {
                // Do nothing as auth is false.
            }
            else
            {
                // Check permissions and set auth = true if permission is valid.
                auth = true;
            }

            return auth;
        }

        /* not using
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            var tmp = filterContext.HttpContext.Session;
        }
        */
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            // Todo - direct to "unauth page"
            base.HandleUnauthorizedRequest(filterContext);
        }
    }

用法:

public class Some_OtherController : /*PossibleNamespace?.*/ControllerBase
    {

        [PermissionAuthorize("somepermission")] // This was a CRUD application thus 1 permission per actionresult
        public ActionResult ViewWhatever()
        {
            ....
        }
    }