Basic validation for ASP. NET Vnext Middleware

Source: Internet
Author: User
Tags httpcontext

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.