It still calls the Web API method, but its not authenticated?
I'm not sure how I get the User authenticated 'before' calling the Web API method?
According to your description, it seems that you want to use Basic Authentication in Web API. Just like your guess, we could enter user name and password straight forward by using Basic Authentication. I have created a simple demo, if I want to read the data in Web API, I need to be authenticated first. You could refer to my code:
Code in Web API project
Create BasicAuthHttpModule.cs: (specific your user name and password)
public class BasicAuthHttpModule : IHttpModule
{
private const string Realm = "My Realm";
public void Init(HttpApplication context)
{
// Register event handlers
context.AuthenticateRequest += OnApplicationAuthenticateRequest;
context.EndRequest += OnApplicationEndRequest;
}
private static void SetPrincipal(IPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
// TODO: Here is where you would validate the username and password.
private static bool CheckPassword(string username, string password)
{
return username == "peter" && password == "Password123!"; // you also could read user name and password from your Azure SQL database
}
private static void AuthenticateUser(string credentials)
{
try
{
var encoding = Encoding.GetEncoding("iso-8859-1");
credentials = encoding.GetString(Convert.FromBase64String(credentials));
int separator = credentials.IndexOf(':');
string name = credentials.Substring(0, separator);
string password = credentials.Substring(separator + 1);
if (CheckPassword(name, password))
{
var identity = new GenericIdentity(name);
SetPrincipal(new GenericPrincipal(identity, null));
}
else
{
// Invalid username or password.
HttpContext.Current.Response.StatusCode = 401;
}
}
catch (FormatException)
{
// Credentials were not formatted correctly.
HttpContext.Current.Response.StatusCode = 401;
}
}
private static void OnApplicationAuthenticateRequest(object sender, EventArgs e)
{
var request = HttpContext.Current.Request;
var authHeader = request.Headers["Authorization"];
if (authHeader != null)
{
var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);
// RFC 2617 sec 1.2, "scheme" name is case-insensitive
if (authHeaderVal.Scheme.Equals("basic",
StringComparison.OrdinalIgnoreCase) &&
authHeaderVal.Parameter != null)
{
AuthenticateUser(authHeaderVal.Parameter);
}
}
}
// If the request was unauthorized, add the WWW-Authenticate header
// to the response.
private static void OnApplicationEndRequest(object sender, EventArgs e)
{
var response = HttpContext.Current.Response;
if (response.StatusCode == 401)
{
response.Headers.Add("WWW-Authenticate",
string.Format("Basic realm=\"{0}\"", Realm));
}
}
public void Dispose()
{
}
}
Code in web.config:
<modules>
<add name="BasicAuthHttpModule"
type=" [your project name].[folder name].BasicAuthHttpModule, [your project name]"/>
<!--Just like this: WebApiAzure1.BasicAuthor.BasicAuthHttpModule,WebApiAzure1-->
</modules>
Code in Api Controller:
[Authorize] //add authorize attribute for specific method
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
You could see the result like this:
