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

时间:2023-03-09 12:56:48
DotNetOpenAuth实践之Webform资源服务器配置

系列目录:

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

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

一、环境搭建

1、新建Webform项目

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

2、使用Nuget添加DotNetOpenAuth 5.0.0 alpha3

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

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

二、编写关键代码

1、公共代码

ResourceServerConfiguration

 using System.Security.Cryptography.X509Certificates;

 namespace WebformResourcesServer.Code
{
public class ResourceServerConfiguration
{
public X509Certificate2 EncryptionCertificate { get; set; }
public X509Certificate2 SigningCertificate { get; set; }
}
}

Common.cs

 namespace WebformResourcesServer.Code
{
public class Common
{
public static ResourceServerConfiguration Configuration = new ResourceServerConfiguration();
}
}

Global

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
using WebformResourcesServer.Code; namespace WebformResourcesServer
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
Common.Configuration = new ResourceServerConfiguration
{
EncryptionCertificate = new X509Certificate2(Server.MapPath("~/Certs/idefav.pfx"), "a"),
SigningCertificate = new X509Certificate2(Server.MapPath("~/Certs/idefav.cer"))
};
// 在应用程序启动时运行的代码
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}

2、关键代码

ashxhandler

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth2; namespace WebformResourcesServer.Code
{
public class AshxHandler
{
public AshxHandler(HttpContext context)
{
Context = context;
} public HttpContext Context { get; set; } private async Task<IPrincipal> VerifyOAuth2(HttpRequestBase httpDetails, params string[] requiredScopes)
{
var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer((RSACryptoServiceProvider)Common.Configuration.SigningCertificate.PublicKey.Key, (RSACryptoServiceProvider)Common.Configuration.EncryptionCertificate.PrivateKey));
return await resourceServer.GetPrincipalAsync(httpDetails, requiredScopes: requiredScopes); } public async Task Proc(Action<HttpContext> action)
{
try
{
var principal = await VerifyOAuth2(new HttpRequestWrapper(Context.Request));
if (principal != null)
{
Context.User = principal;
Thread.CurrentPrincipal = principal;
action.Invoke(Context);
}
}
catch (ProtocolFaultResponseException exception)
{
var outgoingResponse = await exception.CreateErrorResponseAsync(CancellationToken.None);
Context.Response.StatusCode = (int)outgoingResponse.StatusCode;
//Context.Response.SuppressContent = true;
foreach (var header in outgoingResponse.Headers)
{ //Context.Response.Headers[header.Key] = header.Value.First();
Context.Response.AddHeader(header.Key, header.Value.First());
}
Context.Response.Write(exception.Message);
}
}
}
}

3、添加一个ashx文件

目录:

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

代码:

 using System;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using WebformResourcesServer.Code; namespace WebformResourcesServer.Api
{
/// <summary>
/// Values 的摘要说明
/// </summary>
public class Values : IHttpAsyncHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
} public bool IsReusable
{
get
{
return false;
}
} public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
return new AsyncResult(cb, extraData, new AshxHandler(context).Proc(c =>
{
c.Response.Write("The Data you get!");
})); } public void EndProcessRequest(IAsyncResult result)
{
var r = (AsyncResult)result;
r.Task.Wait(); }
} internal class AsyncResult : IAsyncResult
{
private object _state;
private Task _task;
private bool _completedSynchronously; public AsyncResult(AsyncCallback callback, object state, Task task)
{
_state = state;
_task = task;
_completedSynchronously = _task.IsCompleted;
_task.ContinueWith(t => callback(this), TaskContinuationOptions.ExecuteSynchronously);
} public Task Task
{
get { return _task; }
} public object AsyncState
{
get { return _state; }
} public WaitHandle AsyncWaitHandle
{
get { return ((IAsyncResult)_task).AsyncWaitHandle; }
} public bool CompletedSynchronously
{
get { return _completedSynchronously; }
} public bool IsCompleted
{
get { return _task.IsCompleted; }
}
}
}

4、测试

获取access_token

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

访问api

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

如果token不正确

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

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