转载

DotNetOpenAuth实践之WebApi资源服务器

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

一、环境搭建

1、新建WebAPI项目

DotNetOpenAuth实践之WebApi资源服务器

2、利用Nuget添加DotNetOpenAuth

DotNetOpenAuth实践之WebApi资源服务器

注意:

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

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

DotNetOpenAuth实践之WebApi资源服务器

二、关键代码编写

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、设置要验证的接口

DotNetOpenAuth实践之WebApi资源服务器

三、测试

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

DotNetOpenAuth实践之WebApi资源服务器

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

DotNetOpenAuth实践之WebApi资源服务器

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

用access_token范围WebAPI接口

DotNetOpenAuth实践之WebApi资源服务器

我们手动改一下Token

DotNetOpenAuth实践之WebApi资源服务器

DotNetOpenAuth实践之WebApi资源服务器

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

正文到此结束
Loading...