How does the AuthorizeCore Method work?

user3284079 picture user3284079 · Jun 3, 2015 · Viewed 11.8k times · Source

My question is how does the AuthorizeCore method work?

For example when I wanted to create custom Authorize attribute I found that a lot of programmers use this code

var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
  {
    return false;
  }

and then they write their own code.

So what is the role that this piece of code plays, and does the method checks only for the windows users like the administrator and other created users in the computer management else if we customize it to be used in the form authentication.

Also I found this code but I do not understand why the developer stored the user in a cookie and session instead of the session only.

In PHP I used to store the user in a session only and check if he exist in the session or not.

Answer

less picture less · Jun 3, 2015

It is open source, the code can be found here:

https://github.com/aspnet/AspNetWebStack/blob/master/src/System.Web.Mvc/AuthorizeAttribute.cs

And here the specific method:

    // This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.
    protected virtual bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null)
        {
            throw new ArgumentNullException("httpContext");
        }

        IPrincipal user = httpContext.User;
        if (!user.Identity.IsAuthenticated)
        {
            return false;
        }

        if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))
        {
            return false;
        }

        if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))
        {
            return false;
        }

        return true;
    }

Hope that helps.