DotNetOpenAuth实践之Webform资源服务器配置

系列目录:

DotNetOpenAuth实践系列(源码在这里)

上篇我们讲到WebApi资源服务器配置,这篇我们说一下Webform下的ashx,aspx做的接口如何使用OAuth2认证

一、环境搭建

1、新建Webform项目

2、使用Nuget添加DotNetOpenAuth 5.0.0 alpha3

3、把上次制作的证书文件拷贝的项目中

二、编写关键代码

1、公共代码

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.Code
2 {
3     public class Common
4     {
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 WebformResourcesServer
13 {
14     public class Global : HttpApplication
15     {
16         void Application_Start(object sender, EventArgs e)
17         {
18             Common.Configuration = new ResourceServerConfiguration
19             {
20                 EncryptionCertificate = new X509Certificate2(Server.MapPath("~/Certs/idefav.pfx"), "a"),
21                 SigningCertificate = new X509Certificate2(Server.MapPath("~/Certs/idefav.cer"))
22             };
23             // 在应用程序启动时运行的代码
24             RouteConfig.RegisterRoutes(RouteTable.Routes);
25             BundleConfig.RegisterBundles(BundleTable.Bundles);
26         }
27     }
28 }

2、关键代码

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.Code
15 {
16     public class AshxHandler
17     {
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             try
35             {
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、添加一个ashx文件

目录:

代码:

 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     /// Values 的摘要说明
11     /// </summary>
12     public class Values : IHttpAsyncHandler
13     {
14 
15         public void ProcessRequest(HttpContext context)
16         {
17             context.Response.ContentType = "text/plain";
18         }
19 
20         public bool IsReusable
21         {
22             get
23             {
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 : IAsyncResult
47     {
48         private object _state;
49         private Task _task;
50         private bool _completedSynchronously;
51 
52         public AsyncResult(AsyncCallback callback, object state, Task 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 Task
61         {
62             get { return _task; }
63         }
64 
65 
66         public object AsyncState
67         {
68             get { return _state; }
69         }
70 
71         public WaitHandle AsyncWaitHandle
72         {
73             get { return ((IAsyncResult)_task).AsyncWaitHandle; }
74         }
75 
76         public bool CompletedSynchronously
77         {
78             get { return _completedSynchronously; }
79         }
80 
81         public bool IsCompleted
82         {
83             get { return _task.IsCompleted; }
84         }
85     }
86 }

4、测试

获取access_token

访问api

如果token不正确

到这篇为止,本系列基本结束,如果有不明白的地方可以评论留言,感谢大家的关注

原文地址:https://www.cnblogs.com/idefav2010/p/DotNetOpenAuth_WebformResourcesServer.html