Search code examples
c#asp.nethttpbasic-authenticationhttp-status-code-401

Send BASIC auth by default, rather than wait for HTTP 401


I have a web service that requires a BASIC authentication header to be present in the request, or the service will return an HTTP 401 (unauthorized). This works - when the challenge comes back, the browser (in this case, Chrome) pops up and asks for the credentials. They are then saved for future requests.

My problem is that now two requests are being made on each subsequent request to the service - one without auth (which receives a 401), and then the browser immediately replies with the correct auth in the header.

Is there a way to force the browser (maybe via a special header) to supply credentials without having to be explicitly asked by the web service every time?


Solution

  • I do not believe it is possible to force the browser to preempt the 401. When a request for your service is made the service responds with HTTP 401 and adds the WWW-Authenticate Basic header as well as, I'm guessing, a realm (which you can define).

    It would be worth taking a look at the RFC for basic authentication which goes into details in how the basic authentication standards should be implement. http://www.ietf.org/rfc/rfc2617.txt

    You can also look into implementing your own HTTP Module which should give you more flexibility in your application and how you handle basic authentication. This allows you to register event handlers for Authenticate and End Request events and dictate with a bit more clarity how your service will deal with basic auth. A primer for this is available on the asp.net website. http://www.asp.net/web-api/overview/security/basic-authentication

    If your services utilize different authentication based on your applications authentication (e.g. the service will only use basic authentication when the application is configured for forms authentication) than using an HTTP Module will allow you to conditionally use basic authentication. I typically register my handlers in this scenario like this:

    AuthenticationSection config = (AuthenticationSection)WebConfigurationManager.GetSection("system.web/authentication");
    
    if(config.Mode == AuthenticationMode.Forms)
    {
        module.Authenticate += OnEnter;
        context.EndRequest += OnLeave;
    }