Series Catalog:
Dotnetopenauth Practice Series (source is here)
In the previous article we talked about the WCF service as a resource server interface to provide data services, then this article describes Webapi as a resource server, starting with:
First, Environment construction
1. New WEBAPI Project
2. Add Dotnetopenauth with NuGet
Attention:
5.0. 0 Alpha3 has a bug, to GitHub (Dotnetopenauth) inside the source code to compile themselves, with the compiled DLL to replace the NuGet referenced DLL
3. Copy the last-produced certificate file in the project
Second, the key code to write
1. Public code
Resourceserverconfiguration
1 usingSystem.Security.Cryptography.X509Certificates;2 3 namespaceWebapiresourcesserver.code4 {5 Public classresourceserverconfiguration6 {7 PublicX509Certificate2 Encryptioncertificate {Get;Set; }8 PublicX509Certificate2 Signingcertificate {Get;Set; }9 }Ten}
Common.cs
1 namespace Webapiresourcesserver.code 2 {3 Public class Common 4 {5public staticnew Resourceserverconfiguration (); 6 }7 }
Global.cs
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Security.Cryptography.X509Certificates;5 usingsystem.web;6 usingSystem.Web.Http;7 usingSYSTEM.WEB.MVC;8 usingSystem.Web.Optimization;9 usingSystem.Web.Routing;Ten usingWebapiresourcesserver.code; One A namespaceWebapiresourcesserver - { - Public classWebApiApplication:System.Web.HttpApplication the { - protected voidApplication_Start () - { -Common.configuration =Newresourceserverconfiguration + { -Encryptioncertificate =NewX509Certificate2 (Server.MapPath ("~/certs/idefav.pfx"),"a"), +Signingcertificate =NewX509Certificate2 (Server.MapPath ("~/certs/idefav.cer")) A }; at Arearegistration.registerallareas (); - globalconfiguration.configure (webapiconfig.register); - filterconfig.registerglobalfilters (globalfilters.filters); - routeconfig.registerroutes (routetable.routes); - bundleconfig.registerbundles (bundletable.bundles); - } in } -}
Attention:
Here is a place to note, is the authentication server with public key encryption, in the resource server to be decrypted with the private key, so resourceserveconfiguration inside the certificate is and authentication server inside is swapped
2. Rewrite Delegatinghandler
1 usingdotnetopenauth.oauth2;2 usingSystem;3 usingSystem.Net.Http;4 usingSystem.Security.Cryptography;5 usingSystem.Security.Principal;6 usingSystem.Threading;7 usingSystem.Threading.Tasks;8 usingsystem.web;9 Ten namespaceWebapiresourcesserver.code One { A Public classOauth2handler:delegatinghandler - { - Private Static AsyncTask<iprincipal> VerifyOAuth2 (Httprequestmessage httpdetails,params string[] requiredscopes) the { - //for this sample where the Auth server and resource server is the same site, - //we use the same public/private key. - varResourceserver =NewResourceserver (NewStandardaccesstokenanalyzer ((RSACryptoServiceProvider) Common.Configuration.SigningCertificate.PublicKey.Key, (RSACryptoServiceProvider) Common.Configuration.EncryptionCertificate.PrivateKey)); + return awaitResourceserver.getprincipalasync (Httpdetails, requiredscopes:requiredscopes); - } + A protected OverrideTaskSendAsync (httprequestmessage request, CancellationToken CancellationToken) at { - if(Request. Headers.authorization! =NULL&& request. Headers.Authorization.Scheme = ="Bearer") - { - - varPrincipal =VerifyOAuth2 (request); - in if(Principal. Result! =NULL) - { toHttpContext.Current.User =principal. Result; +Thread.CurrentPrincipal =principal. Result; - } the * $ }Panax Notoginseng - return Base. SendAsync (Request, cancellationtoken); the } + A } the}
3, App_start/webapiconfig.cs inside add Oauthhandler
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Web.Http;5 usingWebapiresourcesserver.code;6 7 namespaceWebapiresourcesserver8 {9 Public Static classWebapiconfigTen { One Public Static voidRegister (httpconfiguration config) A { - //Web API Configuration and Services -Config. Messagehandlers.add (NewOauth2handler ()); the //Web API Routing - CONFIG. Maphttpattributeroutes (); - - CONFIG. Routes.maphttproute ( +Name"Defaultapi", -Routetemplate:"Api/{controller}/{id}", +DefaultsNew{id =Routeparameter.optional} A ); at } - } -}
4. Set the interface to be validated
Third, testing
Open Solution Properties, set Startup Project, start authentication server and WEBAPI resource server
Accessing the authentication server using the Post tool get Access_token
This token is valid for 5 minutes and will take more than 5 minutes to get it back.
Webapi interface with Access_token range
Let's change the token manually.
In the next chapter, we'll look at WebForm's ashx interface. How to do the resource server implementation authorization
Dotnetopenauth Practice of WEBAPI Resource server