HTTP Message Handler
Several implementation mechanisms are explained in Web API 2 authentication and authorization, this article explains the implementation of Message Handler in detail.
For message Handler where the request to response process is located, you can refer to the HTTP message handlers
Authentication Message Handler
Take a look at the implementation of the code, and then do the explanation, the complete code can be referenced on Github, webapi2.authentication
1 usingSystem;2 usingSystem.Net;3 usingSystem.Net.Http;4 usingSystem.Security.Claims;5 usingSystem.Threading;6 usingSystem.Threading.Tasks;7 //webprint.framework Referencehttps://github.com/LeafDuan/WebPrint/tree/master/WebPrint.Framework8 usingwebprint.framework;9 Ten namespaceServer.helper One { A //References - // Http://www.codeproject.com/Articles/630986/Cross-Platform-Authentication-With-ASP-NET-Web-API - // http://dgandalf.github.io/WebApiTokenAuthBootstrap/ the Public classAuthenticationmessagehandler:delegatinghandler - { - protected OverrideTaskSendAsync (httprequestmessage request, - cancellationtoken CancellationToken) + { - if(Request. Headers.authorization = =NULL) + { A varReply = Request. Createresponse (httpstatuscode.unauthorized,"Missing Authorization token."); at - returnTask.fromresult (reply); - } - - Try - { in varEncryptedtoken =request. Headers.Authorization.Parameter; - vartoken =Token.decrypt (encryptedtoken); to //BOOL Isvaliduser + varIsipmathes =token. Clientip.equalto (Request. Getclinetip ()); - the if(!isipmathes) * { $ varReply = Request. Createresponse (httpstatuscode.unauthorized,"Invalid Authorization Token");Panax Notoginseng returnTask.fromresult (reply); - } the + varPrincipal =NewClaimsPrincipal (NewClaimsidentity (New[] A { the NewClaim (claimtypes.name, token. Userid.tostring ()) +},"Basic")); - $ //Authorize attribute $Request. Getrequestcontext (). Principal =principal; - } - Catch(Exception ex) the { - varReply =request. Createerrorresponse (Httpstatuscode.unauthorized, ex. Message);Wuyi returnTask.fromresult (reply); the } - Wu return Base. SendAsync (Request, cancellationtoken); - } About } $}
Implementation is also very simple, by inheriting the Delegatinghandler rewrite SendAsync method implementation, the entire process requires the following steps:
1 login, receive login information via Api/auth, verify that it becomes a token
2 each request is judged. The headers.authorization parameter to see if you are carrying tokens (the Http Client sets the token in step 1 to request. Headers.authorization)
3 Parse token, set the Principal of the request context for use with authorize attribute
The basic process is almost the trilogy, where the verification of tokens, such as whether to timeout, whether to repeat, you can find a way to achieve
Web Api Config
As we all know, Message Handler is run before controller in pipeline, so request all API controller will execute Handler first, so for login, need to give extra care, allow anonymous access, implement method: Ha The Ndler can be global or per router, so this is done in the latter way:
1 usingSystem.Linq;2 usingSystem.Net.Http.Formatting;3 usingSystem.Web.Http;4 usingSystem.Web.Http.Dispatcher;5 usingNewtonsoft.json;6 usingServer.helper;7 8 namespaceServer9 {Ten Public Static classWebapiconfig One { A Public Static voidRegister (httpconfiguration config) - { - CONFIG. Maphttpattributeroutes (); the - CONFIG. Routes.maphttproute ( -Name"Authentication", -Routetemplate:"Api/auth", +DefaultsNew{controller =" Account"} - ); + A CONFIG. Routes.maphttproute ( atName"Defaultapi", -Routetemplate:"Api/{controller}/{id}", -DefaultsNew{id =routeparameter.optional}, -ConstraintsNULL, -HandlerNewAuthenticationmessagehandler {Innerhandler =Newhttpcontrollerdispatcher (config)} - ); in - varJsonformatter = config. Formatters.oftype<jsonmediatypeformatter>(). First (); to +JsonFormatter.SerializerSettings.ReferenceLoopHandling =Referenceloophandling.ignore; -JsonFormatter.SerializerSettings.ContractResolver =Newnhibernatecontractresolver (); the } * } $}
Summarize
The recent rush to use Web Api 2, hosted on the Owin self host, encountered a lot of problems, many also rushed to resolve, here also in a hurry to do a share.