系列目录:

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

上篇我们讲到WCF服务作为资源服务器接口提供数据服务,那么这篇我们介绍WebApi作为资源服务器,下面开始:

一、环境搭建

1、新建WebAPI项目

2、利用Nuget添加DotNetOpenAuth

注意:

Nuget里面的 NotNetOpenAuth 5.0. alpha3有bug,要到github(DotNetOpenAuth)里面下源码自己编译,用编译的dll替换掉Nuget引用的dll

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

二、关键代码编写

1、公共代码

ResourceServerConfiguration

 using System.Security.Cryptography.X509Certificates;

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

Common.cs

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

Global.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using WebApiResourcesServer.Code; namespace WebApiResourcesServer
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
Common.Configuration = new ResourceServerConfiguration
{
EncryptionCertificate = new X509Certificate2(Server.MapPath("~/Certs/idefav.pfx"), "a"),
SigningCertificate = new X509Certificate2(Server.MapPath("~/Certs/idefav.cer"))
};
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}

注意:

这里有个地方要注意,就是认证服务器上面用公钥加密,在资源服务器要用私钥解密,所以ResourceServeConfiguration里面传进去的证书是和认证服务器里面的是对调的

2、重写DelegatingHandler

 using DotNetOpenAuth.OAuth2;
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Web; namespace WebApiResourcesServer.Code
{
public class OAuth2Handler : DelegatingHandler
{
private static async Task<IPrincipal> VerifyOAuth2(HttpRequestMessage httpDetails, params string[] requiredScopes)
{
// for this sample where the auth server and resource server are the same site,
// we use the same public/private key.
var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer((RSACryptoServiceProvider)Common.Configuration.SigningCertificate.PublicKey.Key, (RSACryptoServiceProvider)Common.Configuration.EncryptionCertificate.PrivateKey));
return await resourceServer.GetPrincipalAsync(httpDetails, requiredScopes: requiredScopes);
} protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Headers.Authorization != null && request.Headers.Authorization.Scheme == "Bearer")
{ var principal =VerifyOAuth2(request); if (principal.Result != null)
{
HttpContext.Current.User = principal.Result;
Thread.CurrentPrincipal = principal.Result;
} } return base.SendAsync(request, cancellationToken);
} }
}

3、App_Start/WebApiConfig.cs里面添加OAuthHandler

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using WebApiResourcesServer.Code; namespace WebApiResourcesServer
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
config.MessageHandlers.Add(new OAuth2Handler());
// Web API 路由
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}

4、设置要验证的接口

三、测试

打开解决方案属性,设置启动项目,启动认证服务器和WebApi资源服务器

利用Post工具访问认证服务器获取access_token

本次获取的Token的有效期为5分钟,超过5分钟要重新获取

用access_token范围WebAPI接口

我们手动改一下Token

下篇我们看一下Webform的ashx做的接口如何做资源服务器实现Authorization

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

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

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

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

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

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

    系列目录: DotNetOpenAuth实践系列(源码在这里) 上篇我们讲到WebApi资源服务器配置,这篇我们说一下Webform下的ashx,aspx做的接口如何使用OAuth2认证 一.环境搭建 ...

  4. DotNetOpenAuth实践系列

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

  5. DotNetOpenAuth实践

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

  6. DotNetOpenAuth实践之Windows签名制作

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

  7. 【AaronYang第一讲】ASP.NET MVC企业开发的基本环境[资源服务器概念]

    学完了ASP.NET MVC4 IN ACTION 六波以后 企业开发演习 标签:AaronYang  茗洋  EasyUI1.3.4   ASP.NET MVC 3 本篇博客地址:http://ww ...

  8. rsync+inotify 实现资源服务器的同步目录下的文件变化时,备份服务器的同步目录更新,以资源服务器为准,去同步其他客户端

    测试环境: 资源服务器(主服务器):192.168.200.95 备份服务器(客户端):192.168.200.89 同步目录:/etc/test 同步时使用的用户名hadoop密码12345 实验目 ...

  9. 使用Node.js搭建静态资源服务器

    对于Node.js新手,搭建一个静态资源服务器是个不错的锻炼,从最简单的返回文件或错误开始,渐进增强,还可以逐步加深对http的理解.那就开始吧,让我们的双手沾满网络请求! Note: 当然在项目中如 ...

随机推荐

  1. EXT 翻页后查询 页数不重置

    测试查询条件时,当表格翻页后,输入查询条件,页数不刷新,还是之前的页数,导致列表不显示数据.只要在查询时,将表格的currentPage 设为1 即可. store.currentPage = 1; ...

  2. selenium - webdriver - cookie操作

    WebDriver提供了操作Cookie的相关方法,可以读取.添加和删除cookie信息. WebDriver操作cookie的方法: get_cookies(): 获得所有cookie信息. get ...

  3. Codeforces 934.C A Twisty Movement

    C. A Twisty Movement time limit per test 1 second memory limit per test 256 megabytes input standard ...

  4. STL源码分析-vector

    http://note.youdao.com/noteshare?id=55dc651a7489f1413b3a3169401dcf94

  5. Linux iptables:场景实战一

    <Linux iptables:规则原理和基础>和<Linux iptables:规则组成>介绍了iptables的基础及iptables规则的组成,本篇通过实际操作进行ipt ...

  6. P值解释和误区

    sklearn实战-乳腺癌细胞数据挖掘(博主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005269003&am ...

  7. Exponential Distribution指数分布

    sklearn实战-乳腺癌细胞数据挖掘(博主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005269003&am ...

  8. oracle分析函数 (转)

    一.总体介绍 12.1 分析函数如何工作 语法 FUNCTION_NAME(<参数>,…) OVER (<PARTITION BY 表达式,…> <ORDER BY 表达 ...

  9. JAVA中反射机制三

    声明:如需转载请说明地址来源:http://www.cnblogs.com/pony1223 反射三 利用反射获取对象的方法,并调用方法 1.利用反射获取对象的方法,我们仍然利用上面的Person类, ...

  10. opencv 高级拼接函数Stitcher

    Stitcher https://docs.opencv.org/trunk/d8/d19/tutorial_stitcher.html http://blog.csdn.net/czl389/art ...