DotNetOpenAuth实践之WebApi资源服务器

系列目录:

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

 

 

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

 

一、环境搭建

1、新建WebAPI项目

 

 

2、利用Nuget添加DotNetOpenAuth

注意:

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

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

二、关键代码编写

1、公共代码

ResourceServerConfiguration

复制代码
 1 using System.Security.Cryptography.X509Certificates;
 2 
 3 namespace WebApiResourcesServer.Code
 4 {
 5     public class ResourceServerConfiguration
 6     {
 7         public X509Certificate2 EncryptionCertificate { get; set; }
 8         public X509Certificate2 SigningCertificate { get; set; }
 9     }
10 }
复制代码

Common.cs

1 namespace WebApiResourcesServer.Code
2 {
3     public class Common
4     {
5         public static ResourceServerConfiguration Configuration = new ResourceServerConfiguration();
6     }
7 }

Global.cs

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Security.Cryptography.X509Certificates;
 5 using System.Web;
 6 using System.Web.Http;
 7 using System.Web.Mvc;
 8 using System.Web.Optimization;
 9 using System.Web.Routing;
10 using WebApiResourcesServer.Code;
11 
12 namespace WebApiResourcesServer
13 {
14     public class WebApiApplication : System.Web.HttpApplication
15     {
16         protected void Application_Start()
17         {
18             Common.Configuration = new ResourceServerConfiguration
19             {
20                 EncryptionCertificate = new X509Certificate2(Server.MapPath("~/Certs/idefav.pfx"), "a"),
21                 SigningCertificate = new X509Certificate2(Server.MapPath("~/Certs/idefav.cer"))
22             };
23             AreaRegistration.RegisterAllAreas();
24             GlobalConfiguration.Configure(WebApiConfig.Register);
25             FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
26             RouteConfig.RegisterRoutes(RouteTable.Routes);
27             BundleConfig.RegisterBundles(BundleTable.Bundles);
28         }
29     }
30 }
复制代码

注意:

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

2、重写DelegatingHandler

复制代码
 1 using DotNetOpenAuth.OAuth2;
 2 using System;
 3 using System.Net.Http;
 4 using System.Security.Cryptography;
 5 using System.Security.Principal;
 6 using System.Threading;
 7 using System.Threading.Tasks;
 8 using System.Web;
 9 
10 namespace WebApiResourcesServer.Code
11 {
12     public class OAuth2Handler : DelegatingHandler
13     {
14         private static async Task<IPrincipal> VerifyOAuth2(HttpRequestMessage httpDetails, params string[] requiredScopes)
15         {
16             // for this sample where the auth server and resource server are the same site,
17             // we use the same public/private key.
18             var resourceServer = new ResourceServer(new StandardAccessTokenAnalyzer((RSACryptoServiceProvider)Common.Configuration.SigningCertificate.PublicKey.Key, (RSACryptoServiceProvider)Common.Configuration.EncryptionCertificate.PrivateKey));
19             return await resourceServer.GetPrincipalAsync(httpDetails, requiredScopes: requiredScopes);
20         }
21 
22         protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
23         {
24             if (request.Headers.Authorization != null && request.Headers.Authorization.Scheme == "Bearer")
25             {
26                 
27                 var principal =VerifyOAuth2(request);
28 
29                 if (principal.Result != null)
30                 {
31                     HttpContext.Current.User = principal.Result;
32                     Thread.CurrentPrincipal = principal.Result;
33                 }
34                
35                 
36             }
37 
38             return base.SendAsync(request, cancellationToken);
39         }
40 
41     }
42 }
复制代码

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

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web.Http;
 5 using WebApiResourcesServer.Code;
 6 
 7 namespace WebApiResourcesServer
 8 {
 9     public static class WebApiConfig
10     {
11         public static void Register(HttpConfiguration config)
12         {
13             // Web API 配置和服务
14             config.MessageHandlers.Add(new OAuth2Handler());
15             // Web API 路由
16             config.MapHttpAttributeRoutes();
17 
18             config.Routes.MapHttpRoute(
19                 name: "DefaultApi",
20                 routeTemplate: "api/{controller}/{id}",
21                 defaults: new { id = RouteParameter.Optional }
22             );
23         }
24     }
25 }
复制代码

4、设置要验证的接口

三、测试

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

 

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

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

用access_token范围WebAPI接口

 

我们手动改一下Token

 

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

posted on   idefav2010  阅读(3972)  评论(13编辑  收藏  举报

编辑推荐:
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
阅读排行:
· 几个技巧,教你去除文章的 AI 味!
· 系统高可用的 10 条军规
· 对象命名为何需要避免'-er'和'-or'后缀
· 关于普通程序员该如何参与AI学习的三个建议以及自己的实践
· AI与.NET技术实操系列(八):使用Catalyst进行自然语言处理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示