0

I have a case where I have to implement multi authentication in my API.

controller.cs:

public class TestController
{
    [Authorize]
    [CustomAuthFilter]
    public async Task<IHttpActionResult> Get()
    {
         return <some object>;
    }
}

My endpoint shall work for both Windows auth and ping auth.

When I remove the Authorize attribute and use only CustomAuthFilter, ping auth works, but Windows auth fails because the HttpContext.Current.User.Identity.Name returns an empty string value which is definitely not present in allowed users list. So the auth fails.

CustomAuthFilterAttribute.cs:

public class CustomAuthFilter:AuthorizeAttribute
{
   protected override bool IsAuthorized(HttpActionContext actionContext)
   {
       var user = HttpContext.Current.User.Identity.Name;//return empty string.
       var isAuthorised = AuthenticateWindows(user);
       //if the user is not authenticated using windows, attempt to authenticate using ping. rest of the code goes here
       return isAuthorised;
   }

   protected bool AuthenticateWindows(string user)
   {
      var usersList = ConfigurationManager.AppSettings["AllowedUsers"].Split(',').ToList();

      if (!usersList.select(x => x.ToUpper()).ToList().Contains(user.ToUpper()))
          return false;

      return true;
   }
}

1 Answer 1

0

The variable HttpContext.Current.User.Identity.Name gets filled through authorization. This variable is meant to be used after authorization has happened, not during the process.

A workaround could be that you call the base method first, which would make sure the field is not empty (if there is a windows user). This will make sure the Windows Username has been set in the Identity field.

public class CustomAuthFilter:AuthorizeAttribute
{
   protected override bool IsAuthorized(HttpActionContext actionContext)
   {
       var isAuthenticated = base.IsAuthorized(actionContext)
       if (!isAuthenticated)
       {
           //If we cannot find a user, we are not authorized and should not continue.
           return false;
       }

       //This now holds the value of your logged in windows user.
       var user = HttpContext.Current.User.Identity.Name; 
       var isAuthorised = AuthenticateWindows(user);
       //Ping authentication code
       return isAuthorised;
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.