简体   繁体   中英

How to execute code on every request within a controller in ASP.NET Web API 2?

I'm using ASP.NET Web API 2. I have a BaseController class that all other controllers derive from. I have the following method in this controller:

protected User GetLoggedInUser()
{
    // Get the id of the logged in user.
    var globalUserId = userProvider.UserId;

    // Return the entity of the logged in user.
    return context.Users.FirstOrDefault(u => u.GlobalUserId == globalUserId);
}

The idea is that I have an Authorize attribute set globally and I get the Id of the logged in user. The users are not stored in the database that I'm connected with - I'm receiving just their Ids from the client. That's why I need to check whether a User entity with the given GlobalUserId exists in my database. Otherwise, I should return 401 / Unauthorized, because unauthorized users should not have access to the methods.

What I'm doing now is I make the following check in all of my methods:

// Get the entity of the logged in user (from the BaseController class).
var userEntity = this.GetLoggedInUser();

// If the user is not found, return 401 / UNAUTHORIZED.
if (userEntity == null)
{
    return Unauthorized();
}

Is there a good way to handle this and somehow not repeat the same code in all of my methods that have an Authorize attribute (as I've wrote above, I've set the Authorize attribute globally, but I have a couple of methods that have the AllowAnonymous attribute, meaning not all of my methods require authorization)?

I know that MessageHandlers are a good way to execute code that should be run in every request/response but in my case I need to check for the Authorize/AllowAnonymous attributes and have a connection to my database, so I'm not sure that this is a good option or an option at all.

You can create a custom authorize attribute and use it instead of the Authorize attribute and override AuthorizeCore method.

    public class CustomAuthorizeAttribute : AuthorizeAttribute  
    {  
       protected override bool AuthorizeCore(HttpContextBase httpContext)  
       { 
         // Get the entity of the logged in user 
         var userEntity = GetLoggedInUser(httpContext);

         // If the user is not found, return false.
         if (userEntity == null)
         {
             return false;
         }
       }

       private User GetLoggedInUser(HttpContextBase httpContext)
       {
         // return the current user
       }
    }

And use it on your controllers like this:

//Custom authentication request
[CustomAuthorizeAttribute]
public ActionResult DoSomething()

//No authentication at all
[AllowAnonymous]
public ActionResult DoSomething

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM