I have setup an ASP.NET Web API. I want to dynamically validate the basic authentication provided (username and web access key) in the header and pass it to the network credentials method I have setup to validate details.
This is my model:
public class Customer
{
public string No_;
public string Name;
public string AccountingLocation;
}
My controller:
public IHttpActionResult Get(string id)
{
try
{
ws.ValidationRegWebService();
Validation.Customer customerVal = new Validation.Customer();
customerVal = ws.validationReg_ws.Read(id);
[...]
}
[...]
}
My network credential method:
public NetworkCredential Credential()
{
NetworkCredential cred = new NetworkCredential
{
UserName = globals.UserName,
Password = globals.Password
};
return cred;
}
How can I pass the authorization details from the client to the network credential method?
In the method, you can get the basic auth header sent by postman like this:
var header = Request.Headers["Authorization"].FirstOrDefault();
if(header == null) throw UnauthorizedException(); // Not sure this exception exists I just made it up
Then decode it, as it simply contains username:password encoded in base64 prefixed with "Basic ":
var encodedValue = authHeader.Substring("Basic ".Length).Trim(); // Now just a b64 string
var decodedValue = Encoding.UTF8.GetString(Convert.FromBase64String(encodedValue));
var values = decodedValue.Split(":");
var username = values[0];
var password = values[1];