Dotnetopenauth Practice of WEBAPI Resource server

Source: Internet
Author: User

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


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


1 usingSystem.Security.Cryptography.X509Certificates;2 3 namespaceWebapiresourcesserver.code4 {5      Public classresourceserverconfiguration6     {7          PublicX509Certificate2 Encryptioncertificate {Get;Set; }8          PublicX509Certificate2 Signingcertificate {Get;Set; }9     }Ten}


1 namespace Webapiresourcesserver.code 2 {3      Public class Common 4     {5public         staticnew  Resourceserverconfiguration (); 6     }7 }


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     } -}


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

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: 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.