This is a slight variation on the accepted answer. My scenario is that I have a n Asp.net (4.5.2) Controller which works as both an API, as well as a page that just returns to say "You have successfully connected to the Server." The purpose of this is so that the Basic Auth could be tested to ensure it is working before trying to use it with the API. Note that this is a legacy app and requirements stipulate the use of basic auth which is why it is still needed.
The problem is that the rest of the site is set up with FormsAuthentication, so when the BasicAuthenticationFilter would run, it would change the result from a 401 unauthorized to a 302 redirect and the user would end up on the login page.
What I really wanted was for the Basic Auth popup to show in the browser. Again this is only so the end user could test the credentials. This is what I had to change to get this to work:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var req = filterContext.HttpContext.Request;
var auth = req.Headers["Authorization"];
if (!String.IsNullOrEmpty(auth))
{
var cred =System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(auth.Substring(6))).Split(':');
var user = new { Name = cred[0], Pass = cred[1] };
if (user. Name == Username && user. Pass == password) return;
}
filterContext.HttpContext.Response.AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Ryadel"));
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.HttpContext.Response.End();
}
Note that using this line:
filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
did NOT actually suppress the Forms Redirect ( don't know why, seems like it should).
[HttpGet]
[BasicAuthentication("TestUserName", "Abc123*")]
public ActionResult Submit()
{
return new ContentResult() { Content = "You have successfully connected to the AP&G GISB Server." };
}
Also note that the actual implementation checks a database for the username and password, the above is just demo code.