Search code examples
asp.net-web-api2basic-authentication

How to obtain basic authentication username/password in Controller for .NET Web API 2.0


I've read through the documents on how to create a Basic Authentication filter for the Web API 2.0, and it doesn't seem too bad. However..

The issue I have is that I also need the username and password information within the Controller itself (on a POST / PUT / DELETE) to be able to pass through to a 3rd party .NET API for authentication/authorization of an action taken by the Controller.

Is there a 'proper way' to do this?

I can see that the RequestContext (in the Controller) includes info on the Principal. But this only seems to go so far as the Name... so it doesn't have the password that I'd need to pass through to the 3rd party interface.


Solution

  • Basic authentications converts username:password into base64, so all you need is to extract Authorization header and decode it's value:

    AuthenticationHeaderValue authenticationHeaderValue = Request.Headers.Authorization;
    var userNamePasswordString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationHeaderValue.Parameter));
    //username:password