DotNetOpenAuth practices-Webform resource server configuration, authpuppy Server

Source: Internet
Author: User

DotNetOpenAuth practices-Webform resource server configuration, authpuppy Server

Series directory:

DotNetOpenAuth practice series (source code here)

 

In the previous article, we will talk about WebApi resource server configuration. In this article, we will talk about how to use oau2authenticate for the ashx and aspx interfaces in Webform.

 

I. Environment Construction

 

1. Create a Webform Project

 

2. Use Nuget to add DotNetOpenAuth 5.0.0 alpha3

3. Copy the last Certificate file in the project

Ii. Write key code

1. Public Code

ResourceServerConfiguration

 1 using System.Security.Cryptography.X509Certificates; 2  3 namespace WebformResourcesServer.Code 4 { 5     public class ResourceServerConfiguration 6     { 7         public X509Certificate2 EncryptionCertificate { get; set; } 8         public X509Certificate2 SigningCertificate { get; set; } 9     }10 }

Common. cs

1 namespace WebformResourcesServer.Code2 {3     public class Common4     {5         public static ResourceServerConfiguration Configuration = new ResourceServerConfiguration();6     }7 }

Global

1 using System; 2 using System. collections. generic; 3 using System. linq; 4 using System. security. cryptography. x509Certificates; 5 using System. web; 6 using System. web. optimization; 7 using System. web. routing; 8 using System. web. security; 9 using System. web. sessionState; 10 using WebformResourcesServer. code; 11 12 namespace WebformResourcesServer13 {14 public class Global: HttpApplication15 {16 void Application_Start (object sender, EventArgs e) 17 {18 Common. Configuration = new ResourceServerConfiguration19 {20 EncryptionCertificate = new X509Certificate2 (Server. MapPath ("~ /Certs/idefav. pfx ")," a "), 21 SigningCertificate = new X509Certificate2 (Server. MapPath ("~ /Certs/idefav. cer ") 22}; 23 // code 24 RouteConfig. registerRoutes (RouteTable. routes); 25 BundleConfig. registerBundles (BundleTable. bundles); 26} 27} 28}

2. Key code

Ashxhandler

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Net.Http; 5 using System.Security.Cryptography; 6 using System.Security.Principal; 7 using System.Threading; 8 using System.Threading.Tasks; 9 using System.Web;10 using System.Web.UI;11 using DotNetOpenAuth.Messaging;12 using DotNetOpenAuth.OAuth2;13 14 namespace WebformResourcesServer.Code15 {16     public class AshxHandler17     {18         public AshxHandler(HttpContext context)19         {20             Context = context;21         }22 23         public HttpContext Context { get; set; }24 25         private async Task<IPrincipal> VerifyOAuth2(HttpRequestBase httpDetails, params string[] requiredScopes)26         {27             var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer((RSACryptoServiceProvider)Common.Configuration.SigningCertificate.PublicKey.Key, (RSACryptoServiceProvider)Common.Configuration.EncryptionCertificate.PrivateKey));28             return await resourceServer.GetPrincipalAsync(httpDetails, requiredScopes: requiredScopes);29            30         }31 32         public async Task Proc(Action<HttpContext> action)33         {34             try35             {36                 var principal = await VerifyOAuth2(new HttpRequestWrapper(Context.Request));37                 if (principal != null)38                 {39                     Context.User = principal;40                     Thread.CurrentPrincipal = principal;41                     action.Invoke(Context);42                 }43             }44             catch (ProtocolFaultResponseException exception)45             {46                 var outgoingResponse = await exception.CreateErrorResponseAsync(CancellationToken.None);47                 Context.Response.StatusCode = (int)outgoingResponse.StatusCode;48                 //Context.Response.SuppressContent = true;49                 foreach (var header in outgoingResponse.Headers)50                 {51 52                     //Context.Response.Headers[header.Key] = header.Value.First();53                     Context.Response.AddHeader(header.Key, header.Value.First());54                 }55                 Context.Response.Write(exception.Message);56             }57         }58     }59 }

3. Add an ashx File

Directory:

Code:

1 using System; 2 using System. threading; 3 using System. threading. tasks; 4 using System. web; 5 using WebformResourcesServer. code; 6 7 namespace WebformResourcesServer. api 8 {9 /// <summary> 10 // summary of Values 11 /// </summary> 12 public class Values: IHttpAsyncHandler13 {14 15 public void ProcessRequest (HttpContext context) 16 {17 context. response. contentType = "text/plain"; 18} 19 20 public bool Is Reusable21 {22 get23 {24 return false; 25} 26} 27 28 public IAsyncResult BeginProcessRequest (HttpContext context, AsyncCallback cb, object extraData) 29 {30 return new AsyncResult (cb, extraData, new AshxHandler (context ). proc (c => 31 {32 c. response. write ("The Data you get! "); 33}); 34 35 36} 37 38 public void EndProcessRequest (IAsyncResult result) 39 {40 var r = (AsyncResult) result; 41 r. task. wait (); 42 43} 44} 45 46 internal class AsyncResult: IAsyncResult47 {48 private object _ state; 49 private Task _ task; 50 private bool _ completedSynchronously; 51 52 public AsyncResult (AsyncCallback callback, object state, Task) 53 {54 _ state = state; 55 _ task = task; 56 _ completedSynchronously = _ task. isCompleted; 57 _ task. continueWith (t => callback (this), TaskContinuationOptions. executeSynchronously); 58} 59 60 public Task Task61 {62 get {return _ task;} 63} 64 65 66 public object AsyncState67 {68 get {return _ state ;} 69} 70 71 public WaitHandle AsyncWaitHandle72 {73 get {return (IAsyncResult) _ task ). asyncWaitHandle;} 74} 75 76 public bool CompletedSynchronously77 {78 get {return _ completedSynchronously;} 79} 80 81 public bool IsCompleted82 {83 get {return _ task. isCompleted;} 84} 85} 86}

4. Test

Get access_token

Access api

If the token is incorrect

 

So far, this series has basically ended. If you have any questions, you can leave a comment. Thank you for your attention.

Related Article

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.