Breve guida per creare una Web Api 2.0 in C# che utilizzi una Basic Access Authentication (Basic HTTP).

L’implementazione HTTP Basic authentication (BA) è la più semplice tecnica per consentire l’accesso a risorse web con controllo di accesso perché non richiede cookie, id di sessione e pagine di login. Basic authentication utilizza headers HTTP statici e standard che non richiedono handshake eseguito preventivamente.

I dati di autenticazione possono essere passati nell’url come ad esempio:

https://username:password@www.example.com/path

La Basic authentication è spesso utilizzata dove è necessario avere url verso aree riservate in cui si possa accedere sistematicamente, specialmente negli shell script o nei file batch.

Per iniziare è necessario creare un progetto del tipo: ASP.NET Web Application (.NET Framework) senza nessun tipo di autenticazione:

Una volta creato il progetto bisogna creare una classe che implementa l’interfaccia IHttpModule:

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 == "test"
 && password == "test";
 }

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()
 {
 }
 }

Nel web.config aggiungiamo questo codice:

<system.webServer>    
   <modules> 
     <add name="BasicAuthHttpModule" type="WebHostBasicAuth.Modules.BasicAuthHttpModule, YourAssemblyName"/>    </modules>

Inseriamo sopra il controller il DataAnnotation: [Authorize] cosi facendo tutte le request a quel controller dovranno essere autenticate. Per fare un esempio l’ho aggiunto sopra il controller creato di default da visual studio “ValuesController“:

 [Authorize]
 public class ValuesController : ApiController

Ora utilizziamo Postman per fare la chiamata al nostro servizio in locale dopo averlo ovviamente avviato:

Come potete notare è necessario inserire nell’headers la key: “Authorization” con value: “Basic dGVzdDp0ZXN0”

Il valore dGVzdDp0ZXN0 sta per test:test in formato Base64. Per poter effettuare l’encode delle vostre username e password potete utilizzare questo utile sito online di conversione:

https://www.base64encode.org/

Vi consiglio fortemente di utilizzare il protocollo HTTPS per garantire una sicurezza in più al vostro sistema.

Libri utili

Un saluto e arrivederci al prossimo tutorial!

Comments

  1. It’s really a cool and useful piece of information. I’m happy that you simply shared this helpful information with us.
    Please keep us up to date like this. Thanks for sharing.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *