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;
}
}