问题
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