Get permission from an authorized attribute?

I implemented my own attribute Authorize, and I noticed that it is asking for permission checks when used [Authorize].

Is there a way to get this permission and use it in the current controller that applies the attribute Authorizewithout having to rewrite and request the code in the controller?

+3
source share
1 answer

Yes, you can. If you implemented your Authorize attribute as an ActionFilterAttribute, you can use the ViewData collection to store this information:

    public class RequireRegistrationActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpRequestBase request = filterContext.HttpContext.Request;
        HttpResponseBase response = filterContext.HttpContext.Response;

        if (request != null && 
            response != null)
        {
            bool isAuthenticated = request.IsAuthenticated;
            filterContext.Controller.ViewData["IsAuthenticated"] = isAuthenticated;

            if (!isAuthenticated)
            {
                string url = String.Format(
                   "/?ReturnUrl={0}", 
                   HttpUtility.UrlEncode(request.Url.ToString()));
                response.Redirect(url);
            }
        }
    }
}

acrion :

bool isAuthenticated = (bool)(ViewData["IsAuthenticated"] ?? false);
+3

Source: https://habr.com/ru/post/1726216/


All Articles