user3284079
user3284079

Reputation:

How does the AuthorizeCore Method work?

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.

Upvotes: 16

Views: 14002

Answers (1)

less
less

Reputation: 711

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.

Upvotes: 12

Related Questions