Custom authorize attribute - can I store a value for later?

僤鯓⒐⒋嵵緔 提交于 2019-12-11 14:10:53

问题


I have a custom authorize attribute, which basically simply verifies that a cookie was sent with the request and that it has a value assigned.

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

        bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
                      || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);

        if (skipAuthorization) return;

        var cookie = filterContext.HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];

        if (cookie != null)
        {
            var decCookie = FormsAuthentication.Decrypt(cookie.Value);

            if(decCookie != null)
            {
                if (!string.IsNullOrEmpty(decCookie.UserData))
                {
                    return;
                }
            }
        }

        HandleUnauthorizedRequest(filterContext);
    }

This does what I need, but is it possible for me to store the decCookie.UserData somewhere that it can be accessed in the controller action? I made an extension method which will retrieve it in the controller anyway from the request, but its really just a copy of what the attribute has already done.

So, is there a way I can get away with not having the extension method, and simply store the UserData somewhere for later use in the controller right from the attribute?


回答1:


Use a custom principal and identity, and store whatever data you'd like on the identity. See MVC 3.0, Razor, Custom Principal and Identity. For a good intro. Only disregard the bit about using Application_AuthenticateRequest, that's what your Authorize attribute is for.



来源:https://stackoverflow.com/questions/15097356/custom-authorize-attribute-can-i-store-a-value-for-later

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!