DotNetOpenAuth实践之Webform资源服务器配置
系列目录:
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资源服务器配置的更多相关文章
- DotNetOpenAuth实践之WCF资源服务器配置
系列目录: DotNetOpenAuth实践系列(源码在这里) 上一篇我们写了一个OAuth2的认证服务器,我们也获取到access_token,那么这个token怎么使用呢,我们现在就来揭开 一般获 ...
- DotNetOpenAuth实践之WebApi资源服务器
系列目录: DotNetOpenAuth实践系列(源码在这里) 上篇我们讲到WCF服务作为资源服务器接口提供数据服务,那么这篇我们介绍WebApi作为资源服务器,下面开始: 一.环境搭建 1.新建We ...
- DotNetOpenAuth实践系列
写在前面 本人在研究DotNetOpenAuth的过程中,遇到很多问题,很多坑,花费了很多时间才调通这玩意,现在毫无保留的分享出来,希望博友们可以轻松的上手DotNetOpenAuth,减少爬坑时间. ...
- DotNetOpenAuth实践
DotNetOpenAuth实践之搭建验证服务器 DotNetOpenAuth是OAuth2的.net版本,利用DotNetOpenAuth我们可以轻松的搭建OAuth2验证服务器,不废话,下面我们来 ...
- DotNetOpenAuth实践之搭建验证服务器
系列目录: DotNetOpenAuth实践系列(源码在这里) DotNetOpenAuth是OAuth2的.net版本,利用DotNetOpenAuth我们可以轻松的搭建OAuth2验证服务器,不废 ...
- DotNetOpenAuth实践之Windows签名制作
系列目录: DotNetOpenAuth实践系列(源码在这里) 在上篇中我们搭建了一个简单的认证服务器,里面使用到了Windows签名证书,这一篇则是教大家如何制作Windows签名证书,下面进入正题 ...
- 学习nginx从入门到实践(五) 场景实践之静态资源web服务
一.静态资源web服务 1.1 静态资源 静态资源定义:非服务器动态生成的文件. 1.2 静态资源服务场景-CDN 1.3 文件读取配置 1.3.1 sendfile 配置语法: syntax: se ...
- Kubernetes实践技巧:资源预留
ubernetes 的节点可以按照节点的资源容量进行调度,默认情况下 Pod 能够使用节点全部可用容量.这样就会造成一个问题,因为节点自己通常运行了不少驱动 OS 和 Kubernetes 的系统守护 ...
- nginx静态资源服务器配置
编辑 nginx.conf server { listen 80; server_name file.youxiu326.xin; location /image/ { #访问 file.youxiu ...
随机推荐
- Spring MVC @PathVariable注解
下面用代码来演示@PathVariable传参方式 @RequestMapping("/user/{id}") public String test(@PathVariable(& ...
- Codeforces 892 C.Pride
C. Pride time limit per test 2 seconds memory limit per test 256 megabytes input standard input outp ...
- python基础之列表、字典、元祖等 (二)
一.作用域 if 1==1: name = 'weibinf' print name 下面的结论对吗? 外层变量,可以被内层变量使用 内层变量,无法被外层变量使用 二.三元运算 result = 值1 ...
- 「Django」与mysql8连接的若干问题
1.setting配置 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', #数据库驱动名 'NAME': 'my_tes ...
- libcurl移植到android
一.总体概览 C库:libcurl 3.7 目标平台:android 编译平台:ubuntu 12 编译工具:ndk r7 or later 二.已知方法 1. 官网上给了两种方法,第一种方法是使用a ...
- poi对excel的操作(二)
二.进阶的对象 1.CellType 枚举类 单元格类型 CellType.STRING---文本型 等 如何是指单元格类型:cell.setCellType(CellType.STRING) 2.C ...
- HDU 1573 CRT
CRT模板题 /** @Date : 2017-09-15 13:52:21 * @FileName: HDU 1573 CRT EXGCD.cpp * @Platform: Windows * @A ...
- 超酷动态图片展示墙JS特效制作方法
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 【BZOJ】1901: Zju2112 Dynamic Rankings
[题意]带修改的查询区间第k小 [算法]树状数组套可持久化线段树 [题解]对于树状数组上的每个节点,维护可持久化权值线段树(节点为权值),从而达到查询前缀和的目的. 对于每次修改,在待修改线段树基础上 ...
- 写一个简易浏览器、ASP.NET核心知识(3)
前言 先在文章前面说好了,省得大家发现我根本没有这样的头发,duang的一下一堆人骂我. 这篇文章的标题有点大,其实挺low的,我需要在开头解释一下.我这里只想写一个小的控制台,旨在模拟浏览器的htt ...