Overview
Vnext there is no web. config to configure Basic authentication, this article uses middleware to implement basic validation
Realize
Adding middleware through Startup (startup Class) Configure method
Public void Configure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory) { app. Usemymiddleware ();
// registering middleware through extensions Public Static class basicauthenticationextensions { publicstatic iapplicationbuilder usemymiddleware ( This Iapplicationbuilder app) { return app. Usemiddleware<basicauthentication>(); } }
//Middleware Class Public classbasicauthentication {Private ReadOnlyrequestdelegate Next; Publicbasicauthentication (requestdelegate next) { This. Next =Next; } Public AsyncTask Invoke (HttpContext context, Iauthenticationservice AuthenticationService) { Try { varParser =NewBasicauthenticationparser (context); varUsername =parser. GetUserName (); varPassword =parser. GetPassword (); awaitauthenticationservice.authenticateasync (username, password); awaitNext (context); } Catch(Exception e) {context. Response.statuscode=401; Context. RESPONSE.HEADERS.ADD ("www-authenticate", New[] {"Basic" }); } } }
//Parse context get password user name Internal classBasicauthenticationparser {Private ReadOnly stringcredentials; PublicBasicauthenticationparser (HttpContext context) {credentials=getcredentials (context); } Public stringGetUserName () {returnGetValue (Credentials,0); } Public stringGetPassword () {returnGetValue (Credentials,1); } Private Static stringGetValue (stringCredentialsintindex) { if(string. Isnullorwhitespace (credentials))return NULL; varParts = credentials. Split (':'); returnParts. Length = =2? Parts[index]:NULL; } Private Static stringGetcredentials (HttpContext context) {Try { string[] authheader; if(Context. Request.Headers.TryGetValue ("Authorization", outAuthheader) &&Authheader.any ()&&authheader[0]. StartsWith ("Basic")) { varValue = convert.frombase64string (authheader[0]. Split (' ')[1]); returnEncoding.UTF8.GetString (value); } return NULL; } Catch { return NULL; } } }
//Authentication Service Interface Public InterfaceIauthenticationservice {Task Authenticateasync (stringUsernamestringpassword); } Public classSimpleauthenticationservice:iauthenticationservice { PublicTask Authenticateasync (stringUsernamestringpassword) { //Interpreting Passwords if("123". Equals (username, stringcomparison.ordinalignorecase) &&"123". Equals (password)) {returnTask.fromresult (0); } Throw NewException (); } }
Run effect
Basic validation for ASP. NET Vnext Middleware