系列目录:

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

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

一、环境搭建

1、新建Webform项目

2、使用Nuget添加DotNetOpenAuth 5.0.0 alpha3

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

二、编写关键代码

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文件

目录:

代码:

 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

访问api

如果token不正确

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

DotNetOpenAuth实践之Webform资源服务器配置的更多相关文章

  1. DotNetOpenAuth实践之WCF资源服务器配置

    系列目录: DotNetOpenAuth实践系列(源码在这里) 上一篇我们写了一个OAuth2的认证服务器,我们也获取到access_token,那么这个token怎么使用呢,我们现在就来揭开 一般获 ...

  2. DotNetOpenAuth实践之WebApi资源服务器

    系列目录: DotNetOpenAuth实践系列(源码在这里) 上篇我们讲到WCF服务作为资源服务器接口提供数据服务,那么这篇我们介绍WebApi作为资源服务器,下面开始: 一.环境搭建 1.新建We ...

  3. DotNetOpenAuth实践系列

    写在前面 本人在研究DotNetOpenAuth的过程中,遇到很多问题,很多坑,花费了很多时间才调通这玩意,现在毫无保留的分享出来,希望博友们可以轻松的上手DotNetOpenAuth,减少爬坑时间. ...

  4. DotNetOpenAuth实践

    DotNetOpenAuth实践之搭建验证服务器 DotNetOpenAuth是OAuth2的.net版本,利用DotNetOpenAuth我们可以轻松的搭建OAuth2验证服务器,不废话,下面我们来 ...

  5. DotNetOpenAuth实践之搭建验证服务器

    系列目录: DotNetOpenAuth实践系列(源码在这里) DotNetOpenAuth是OAuth2的.net版本,利用DotNetOpenAuth我们可以轻松的搭建OAuth2验证服务器,不废 ...

  6. DotNetOpenAuth实践之Windows签名制作

    系列目录: DotNetOpenAuth实践系列(源码在这里) 在上篇中我们搭建了一个简单的认证服务器,里面使用到了Windows签名证书,这一篇则是教大家如何制作Windows签名证书,下面进入正题 ...

  7. 学习nginx从入门到实践(五) 场景实践之静态资源web服务

    一.静态资源web服务 1.1 静态资源 静态资源定义:非服务器动态生成的文件. 1.2 静态资源服务场景-CDN 1.3 文件读取配置 1.3.1 sendfile 配置语法: syntax: se ...

  8. Kubernetes实践技巧:资源预留

    ubernetes 的节点可以按照节点的资源容量进行调度,默认情况下 Pod 能够使用节点全部可用容量.这样就会造成一个问题,因为节点自己通常运行了不少驱动 OS 和 Kubernetes 的系统守护 ...

  9. nginx静态资源服务器配置

    编辑 nginx.conf server { listen 80; server_name file.youxiu326.xin; location /image/ { #访问 file.youxiu ...

随机推荐

  1. 图像BMP格式介绍

    1 图像BMP格式说明 BMP是一种与硬件设备无关的图像文件格式,使用非常广.它采用位映射存储格式,除了图像深度可选以外,不采用其他任何压缩,因此,BMP文件所占用的空间很大.BMP文件的图像深度可选 ...

  2. Codeforces Round #338 (Div. 2) D 数学

    D. Multipliers time limit per test 2 seconds memory limit per test 256 megabytes input standard inpu ...

  3. laravel5.1 使用中间表的多对多关联

    用户表user 标签表tag 中间表user_tag(user_id,tag_id) 在user模型中定义tags关联如下: public function tags() { return $this ...

  4. C/C++ string.h头文件小结

    http://note.youdao.com/noteshare?id=cff515f7b683f579d22f17b54b960e2a

  5. Qt ------ 设置透明度

    void setWindowOpacity(qreal level);   //设置所有控件的不透明度 setAttribute(Qt::WA_TranslucentBackground);   // ...

  6. eclipse中修改svn用户名和密码

    开发中有时候用公共的电脑提交一些代码,eclipse没有专门的切换svn账户的功能.查阅资料得出解决办法: 1. 查看你的Eclipse 中使用的是什么SVN Interface  windows & ...

  7. TED_Topic2:My desperate journey with a human smuggler

    My desperate journey with a human smuggler By Barat Ali Batoor When I was a child there was a toy wh ...

  8. 51nod1110 距离之和最小 V3

    基准时间限制:1 秒 空间限制:131072 KB 分值: 40  X轴上有N个点,每个点除了包括一个位置数据X[i],还包括一个权值W[i].该点到其他点的带权距离 = 实际距离 * 权值.求X轴上 ...

  9. 数组B - 我想我需要一艘船屋

    [题目大意]弗雷德先生正在考虑在路易斯安娜州买一块地造房子,在土地调查中,他了解到由于密西西比河的侵蚀,路易斯安那州正以每年50平方英里的速度变小.弗雷德先生想知道他买的那块地是否会被侵蚀掉,经过进一 ...

  10. Broken Necklace

    Description 你有一条由N个红色的,白色的,或蓝色的珠子组成的项链(3<=N<=350),珠子是随意安排的. 这里是 n=29 的二个 例子: 1 2 1 2 r b b r b ...