Basic Authentication in ASP.NET Web API
by Mike Wasson
Basic authentication is defined in RFC 2617, HTTP Authentication: Basic and Digest Access Authentication.
Disadvantages
- User credentials are sent in the request.
- Credentials are sent as plaintext.
- Credentials are sent with every request.
- No way to log out, except by ending the browser session.
- Vulnerable to cross-site request forgery (CSRF); requires anti-CSRF measures.
Advantages
- Internet standard.
- Supported by all major browsers.
- Relatively simple protocol.
Basic authentication works as follows:
- If a request requires authentication, the server returns 401 (Unauthorized). The response includes a WWW-Authenticate header, indicating the server supports Basic authentication.
- The client sends another request, with the client credentials in the Authorization header. The credentials are formatted as the string “name:password”, base64-encoded. The credentials are not encrypted.
Basic authentication is performed within the context of a “realm.” The server includes the name of the realm in the WWW-Authenticate header. The user’s credentials are valid within that realm. The exact scope of a realm is defined by the server. For example, you might define several realms in order to partition resources.
Because the credentials are sent unencrypted, Basic authentication is only secure over HTTPS. See Working with SSL in Web API.
Basic authentication is also vulnerable to CSRF attacks. After the user enters credentials, the browser automatically sends them on subsequent requests to the same domain, for the duration of the session. This includes AJAX requests. See Preventing Cross-Site Request Forgery (CSRF) Attacks.
Basic Authentication with IIS
IIS supports Basic authentication, but there is a caveat: The user is authenticated against their Windows credentials. That means the user must have an account on the server’s domain. For a public-facing web site, you typically want to authenticate against an ASP.NET membership provider.
To enable Basic authentication using IIS, set the authentication mode to “Windows” in the Web.config of your ASP.NET project:
[!code-xmlMain]
1: <system.web>
2: <authentication mode="Windows" />
3: </system.web>
In this mode, IIS uses Windows credentials to authenticate. In addition, you must enable Basic authentication in IIS. In IIS Manager, go to Features View, select Authentication, and enable Basic authentication.
In your Web API project, add the [Authorize]
attribute for any controller actions that need authentication.
A client authenticates itself by setting the Authorization header in the request. Browser clients perform this step automatically. Nonbrowser clients will need to set the header.
Basic Authentication with Custom Membership
As mentioned, the Basic Authentication built into IIS uses Windows credentials. That means you need to create accounts for your users on the hosting server. But for an internet application, user accounts are typically stored in an external database.
The following code how an HTTP module that performs Basic Authentication. You can easily plug in an ASP.NET membership provider by replacing the CheckPassword
method, which is a dummy method in this example.
In Web API 2, you should consider writing an authentication filter or OWIN middleware, instead of an HTTP module.
[!code-csharpMain]
1: namespace WebHostBasicAuth.Modules
2: {
3: public class BasicAuthHttpModule : IHttpModule
4: {
5: private const string Realm = "My Realm";
6:
7: public void Init(HttpApplication context)
8: {
9: // Register event handlers
10: context.AuthenticateRequest += OnApplicationAuthenticateRequest;
11: context.EndRequest += OnApplicationEndRequest;
12: }
13:
14: private static void SetPrincipal(IPrincipal principal)
15: {
16: Thread.CurrentPrincipal = principal;
17: if (HttpContext.Current != null)
18: {
19: HttpContext.Current.User = principal;
20: }
21: }
22:
23: // TODO: Here is where you would validate the username and password.
24: private static bool CheckPassword(string username, string password)
25: {
26: return username == "user" && password == "password";
27: }
28:
29: private static void AuthenticateUser(string credentials)
30: {
31: try
32: {
33: var encoding = Encoding.GetEncoding("iso-8859-1");
34: credentials = encoding.GetString(Convert.FromBase64String(credentials));
35:
36: int separator = credentials.IndexOf(':');
37: string name = credentials.Substring(0, separator);
38: string password = credentials.Substring(separator + 1);
39:
40: if (CheckPassword(name, password))
41: {
42: var identity = new GenericIdentity(name);
43: SetPrincipal(new GenericPrincipal(identity, null));
44: }
45: else
46: {
47: // Invalid username or password.
48: HttpContext.Current.Response.StatusCode = 401;
49: }
50: }
51: catch (FormatException)
52: {
53: // Credentials were not formatted correctly.
54: HttpContext.Current.Response.StatusCode = 401;
55: }
56: }
57:
58: private static void OnApplicationAuthenticateRequest(object sender, EventArgs e)
59: {
60: var request = HttpContext.Current.Request;
61: var authHeader = request.Headers["Authorization"];
62: if (authHeader != null)
63: {
64: var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);
65:
66: // RFC 2617 sec 1.2, "scheme" name is case-insensitive
67: if (authHeaderVal.Scheme.Equals("basic",
68: StringComparison.OrdinalIgnoreCase) &&
69: authHeaderVal.Parameter != null)
70: {
71: AuthenticateUser(authHeaderVal.Parameter);
72: }
73: }
74: }
75:
76: // If the request was unauthorized, add the WWW-Authenticate header
77: // to the response.
78: private static void OnApplicationEndRequest(object sender, EventArgs e)
79: {
80: var response = HttpContext.Current.Response;
81: if (response.StatusCode == 401)
82: {
83: response.Headers.Add("WWW-Authenticate",
84: string.Format("Basic realm=\"{0}\"", Realm));
85: }
86: }
87:
88: public void Dispose()
89: {
90: }
91: }
92: }
To enable the HTTP module, add the following to your web.config file in the system.webServer section:
[!code-xmlMain]
1: <system.webServer>
2: <modules>
3: <add name="BasicAuthHttpModule"
4: type="WebHostBasicAuth.Modules.BasicAuthHttpModule, YourAssemblyName"/>
5: </modules>
Replace “YourAssemblyName” with the name of the assembly (not including the “dll” extension).
You should disable other authentication schemes, such as Forms or Windows auth.
|