Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the Authorize tag work? - ASP.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.

like image 697
chobo2 Avatar asked Aug 29 '09 05:08

chobo2


People also ask

What is the use of Authorize attribute?

Web API provides a built-in authorization filter, AuthorizeAttribute. This filter checks whether the user is authenticated. If not, it returns HTTP status code 401 (Unauthorized), without invoking the action. We can apply the filter globally, at the controller level, or at the level of individual actions.


2 Answers

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.

like image 133
Kelsey Avatar answered Oct 24 '22 08:10

Kelsey


ControllerActionInvoker parses the attribute and calls OnAuthorization() on it when it's time to check the credentials.

The AuthorizationAttribute.OnAuthorization() method basically checks to see if User.Identity.IsAuthenticated is true or not. This just draws on the functionality of FormsAuthentication or whatever other authentication scheme you may be using.

like image 36
womp Avatar answered Oct 24 '22 08:10

womp