系列目录:

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. Machine Learning in Action-chapter2-k近邻算法

    一.numpy()函数 1.shape[]读取矩阵的长度 例: import numpy as np x = np.array([[1,2],[2,3],[3,4]]) print x.shape / ...

  2. 省选模拟赛 LYK loves string(string)

    题目描述 LYK喜欢字符串,它认为一个长度为n的字符串一定会有n*(n+1)/2个子串,但是这些子串是不一定全部都不同的,也就是说,不相同的子串可能没有那么多个.LYK认为,两个字符串不同当且仅当它们 ...

  3. POJ 3171 DP

    Cleaning Shifts Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 3563   Accepted: 1205 D ...

  4. 6.UiWatcher API 详细介绍

    Tip: 1.监听器不是完能的,所以若用例需要设置监听器防止用例被打断,最好把延迟时间调高一点 2.UiDevice是不会触发监听功能的 3.监听器在方法体或者循环体中是程序还是会被打断的 4.监听器 ...

  5. zlib解压缩gzip

    zlib是个著名的开源解压缩库,gzip是一种压缩文件格式. zlib可以压缩原始数据并输出gzip文件,gzip文件中除了压缩数据外,还有描述这些数据的文件头,所以当原始数据较小时,会出现zlib的 ...

  6. .net core 集成 autofac.

    1. Install Install-Package Autofac Install-Package Autofac.Extensions.DependencyInjection 2.Startup ...

  7. 【CodeForces】679 B. Bear and Tower of Cubes

    [题目]B. Bear and Tower of Cubes [题意]有若干积木体积为1^3,2^3,...k^3,对于一个总体积X要求每次贪心地取<=X的最大积木拼上去(每个只能取一次)最后总 ...

  8. 【洛谷 P3191】 [HNOI2007]紧急疏散EVACUATE(二分答案,最大流)

    题目链接 sb错误调了3hour+.. bfs预处理出每个\(.\)到每个\(D\)的最短距离. 二分时间\(t\),把每个\(D\)拆成\(t\)个点,这\(t\)个点两两连边,流量\(INF\)表 ...

  9. 蓝色的cms网站后台管理模板——后台

    链接:http://pan.baidu.com/s/1c138cwC 密码:9vy9

  10. Appium环境搭建说明(包括报错处理)

    Appium环境搭建说明 一.环境配置 前提是windows系统已安装以下软件: 1.jdk 我装的是1.8.0 2.android-sdk 3.python,3.4-3.6 5.Node.js,v8 ...