1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Net.Http.Headers;4 usingSystem.Security.Principal;5 usingSystem.Text;6 usingSystem.Threading;7 usingSystem.Threading.Tasks;8 usingSystem.Web.Http.Filters;9 usingSystem.Web.Http.Results;Ten One namespaceWebApi A { -[AttributeUsage (AttributeTargets.Class |AttributeTargets.Method)] - Public classAuthenticateattribute:filterattribute, Iauthenticationfilter the { - Private Static ReadOnlydictionary<string,string>useraccounts; - - StaticAuthenticateattribute () + { -UserAccounts =Newdictionary<string,string>(stringcomparer.ordinalignorecase) + { A{"Foo","Password"}, at{"Bar","Password"}, -{"Baz","Password"} - }; - } - - PublicTask Authenticateasync (httpauthenticationcontext context, CancellationToken CancellationToken) in { -IPrincipal user =NULL; to varHeadervalue =context. Request.Headers.Authorization; + if(NULL! = Headervalue && Headervalue.scheme = ="Basic") - { the varCredential =Encoding.Default.GetString (convert.frombase64string (Headervalue.parameter)); * varSplit = credential. Split (':'); $ if(split.) Length = =2)Panax Notoginseng { - varUserName = split[0]; the stringpassword; + if(Useraccounts.trygetvalue (UserName, outpassword)) A { the if(Password = = split[1]) + { - varIdentity =Newgenericidentity (userName); $user =NewGenericPrincipal (Identity,New string[0]); $ } - } - } the } -Context. Principal =user;Wuyi returntask.fromresult<Object> (NULL); the } - Wu PublicTask Challengeasync (httpauthenticationchallengecontext context, CancellationToken CancellationToken) - { About varuser =context. ActionContext.ControllerContext.RequestContext.Principal; $ if(NULL! = User && user. identity.isauthenticated)returntask.fromresult<Object> (NULL); - varParameter = $"Realm={context. Request.RequestUri.DnsSafeHost}"; - varChallenge =NewAuthenticationheadervalue ("Basic", parameter); -Context. Result =NewUnauthorizedresult (New[] {challenge}, context. Request); A returntask.fromresult<Object> (NULL); + } the } -}
The ASP. NET Web API implements identity authentication with the authentication feature