I would like to add basic HTTP authorization to the entire site that uses authentication on some secure pages. The idea is to present the portal development phase to the client so that he can play with him, but to ensure the security of the entire site with additional simple logins and passwords at the HTTP level so that no one can access him. The classic tag in web.config is not enough here, because the portal can use forms authentication (with user registration) as part of its functionality. I would like to authorize the user over HTTP before forms authentication, which may happen later.
Authorization at the HTTP level must have logins and passwords configured by the administrator (i.e. in a text file).
Is it possible to achieve this functionality with a custom http module?
UPDATE:
The idea is to create a configuration way to protect the application. Form authentication is not included here, as processing different types and roles of an account will require changes to the application.
I already solved this problem with a simple custom module that checks the header of the HTTP response and the response with HTTP 401. This module can be connected to any website through Web.Config
DECISION:
Module Class:
public class BasicAuthModule : IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(this.HttpApplicationBeginRequest); } private void HttpApplicationBeginRequest(object sender, EventArgs e) { var request = HttpContext.Current.Request; var response = HttpContext.Current.Response; string authHeader = request.Headers["Authorization"]; if (string.IsNullOrEmpty(authHeader)) { this.RequireAuthorization(response); } else { string authType = authHeader.Split(' ').First(); string authData = authHeader.Split(' ').Last(); if (authType.ToLower() == "basic") { byte[] bytes = Convert.FromBase64String(authData); string plainText = Encoding.UTF8.GetString(bytes); string login = plainText.Split(':').First(); string password = plainText.Split(':').Last(); if (!this.Validate(login, password)) { this.DenyAccess(response); } } else { this.DenyAccess(response); } } } private bool Validate(string login, string password) { return (login == ConfigurationManager.AppSettings["AuthLogin"]) && (password == ConfigurationManager.AppSettings["AuthPwd"]); } private void RequireAuthorization(HttpResponse response) { response.AddHeader("WWW-Authenticate", "Basic realm=\"stage\""); response.StatusCode = 401; response.Status = "401 Authorization Required"; response.ContentType = "text/html"; response.End(); } private void DenyAccess(HttpResponse response) { response.AddHeader("WWW-Authenticate", "Basic realm=\"stage\"") response.StatusCode = 401; response.Status = "401 Authorization Required"; response.ContentType = "text/html"; response.End(); } }
In web.config:
<modules runAllManagedModulesForAllRequests="true"> ... <add name="BasicAuthModule" type="MyNamespace.BasicAuthModule, MyNamespace.Module"/> </modules>
source share