Asp.net-mvc – How does the Authorize tag work? – ASP.NET MVC

asp.net-membershipasp.net-mvc

How does the Authorize Tag determine if the user is authorized or not?

Like say, if a user logs in and they try to go to a view that has an Authorize tag. How does it determine if a user is authorized or not? Does it do a query to database and check?

How about if they go to a view with a role authorization? Does it query the membership role table?

I am just wondering since I have what the ASP.NET membership tables considers duplicate userNames. I use a serious of fields to determine which user is what, allowing users to have the same duplicate userName, but still be unique in my database.

This caused me to have to write custom methods for lots of .NET membership stuff since it all used "userName" to do searching instead of using the UserId.

So I am now wondering if this could be the case with the Authorize tag. Since I have no clue how it works and like if I was not using .NET membership I would not have a clue how it would determine it.

Best Answer

The Authorize tag uses all the built in membership checks from ASP.NET. It's VERY easy to role your own tag. For example:

public class MyAuthorize : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext == null) throw new ArgumentNullException("httpContext");

        // Make sure the user is authenticated.
        if (httpContext.User.Identity.IsAuthenticated == false) return false;

        // Do you own custom stuff here
        bool allow = CheckIfAllowedToAccessStuff();

        return allow;
    }
}

You then can use the [MyAuthorize] tag which will use your custom checks.