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:
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!
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.
lipitor 10mg usa lipitor medication how to buy lipitor
purchase ciprofloxacin generic – oral cipro purchase amoxiclav generic
buy cipro generic – keflex 250mg uk buy augmentin 625mg pills
order metronidazole 400mg for sale – buy amoxicillin online azithromycin canada
ciplox 500mg cheap – buy generic trimox
erythromycin cheap
order generic valtrex – mebendazole order buy acyclovir without prescription
buy stromectol uk – sumycin 500mg us tetracycline 500mg price
buy flagyl paypal – flagyl for sale online buy zithromax 250mg without prescription
acillin where to buy order penicillin pill amoxicillin online buy
buy lasix 100mg – prograf over the counter buy capoten without prescription
order glycomet 1000mg pills – buy epivir generic lincocin 500mg brand
retrovir 300mg uk – oral allopurinol
clozapine 50mg cost – perindopril 4mg cost order pepcid 40mg online
quetiapine 50mg sale – buy generic ziprasidone buy eskalith medication
order atarax 25mg for sale – sarafem 20mg tablet cheap endep 25mg
clomipramine 50mg without prescription – tofranil 75mg usa buy generic doxepin
order amoxil pills – buy trimox without prescription ciprofloxacin online order
order augmentin 625mg pills – order linezolid 600mg generic how to get baycip without a prescription
purchase cleocin online – cefixime drug buy chloramphenicol generic
wfhHZXNtqymDVg
buy azithromycin no prescription – buy cheap tindamax generic ciplox
generic asthma pills – order fexofenadine 180mg sale buy theophylline
ivermectin 3mg without prescription – levofloxacin 250mg canada buy cefaclor 500mg pills
buy desloratadine without prescription – buy beclamethasone nasal spray albuterol buy online
buy generic medrol over the counter – astelin 10ml tablet buy generic astelin for sale
micronase for sale – dapagliflozin 10mg usa order forxiga 10 mg generic
buy prandin without prescription – order jardiance 25mg for sale buy jardiance 10mg generic
glucophage without prescription – buy losartan 50mg online cheap generic acarbose 50mg
lamisil 250mg uk – how to get fulvicin without a prescription buy generic grifulvin v
rybelsus 14 mg canada – semaglutide 14 mg cost DDAVP over the counter
ketoconazole pill – lotrisone generic sporanox 100mg