DotNetOpenAuth实践之搭建验证服务器

系列目录:

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

 

 

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

本次搭建环境:

.net4.5.1 ,DotNetOpenAuth v5.0.0-alpha3,MVC5

 

一、环境搭建

  1、新建一个空的VS解决方案

 

  2、添加验证服务器项目,项目选择MVC,不要自带的身份验证

 

  3、使用Nuget添加DotNetOpenAuth v5.0.0-alpha3

输入DotNetOpenAuth 安装DotNetOpenAuth v5.0.0-alpha3

添加完成后

 

二、编写DotNetOpenAuth 验证服务器关键代码,实现功能

  1、添加AuthorizationServerConfiguration.cs

这里的配置是为了添加方便管理,其实可以不用这个类

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Security.Cryptography.X509Certificates;
 5 using System.Web;
 6 
 7 namespace IdefavAuthorizationServer.Code
 8 {
 9     /// <summary>
10     /// 验证服务器配置
11     /// </summary>
12     public class AuthorizationServerConfiguration
13     {
14         /// <summary>
15         /// 构造函数
16         /// </summary>
17         public AuthorizationServerConfiguration()
18         {
19             TokenLifetime = TimeSpan.FromMinutes(5);
20         }
21 
22         /// <summary>
23         /// 签名证书
24         /// </summary>
25         public X509Certificate2 SigningCertificate { get; set; }
26 
27         /// <summary>
28         /// 加密证书
29         /// </summary>
30         public X509Certificate2 EncryptionCertificate { get; set; }
31 
32         /// <summary>
33         /// Token有效时间
34         /// </summary>
35         public TimeSpan TokenLifetime { get; set; }
36     }
37 }

2、实现IClientDescription接口

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using DotNetOpenAuth.Messaging;
 6 using DotNetOpenAuth.OAuth2;
 7 
 8 namespace IdefavAuthorizationServer.Code
 9 {
10     public class Client : IClientDescription
11     {
12         /// <summary>
13         /// 客户端名称client_id
14         /// </summary>
15         public string Name { get; set; }
16 
17         /// <summary>
18         /// 客户端类型
19         /// </summary>
20         public int ClientType { get; set; }
21 
22         /// <summary>
23         /// 回调URL
24         /// </summary>
25         public string Callback { get; set; }
26 
27         public string ClientSecret { get; set; }
28 
29 
30         Uri IClientDescription.DefaultCallback
31         {
32             get { return string.IsNullOrEmpty(this.Callback) ? null : new Uri(this.Callback); }
33         }
34 
35 
36         ClientType IClientDescription.ClientType
37         {
38             get { return (ClientType)this.ClientType; }
39         }
40 
41 
42         bool IClientDescription.HasNonEmptySecret
43         {
44             get { return !string.IsNullOrEmpty(this.ClientSecret); }
45         }
46 
47 
48         bool IClientDescription.IsCallbackAllowed(Uri callback)
49         {
50             if (string.IsNullOrEmpty(this.Callback))
51             {
52                 // No callback rules have been set up for this client.
53                 return true;
54             }
55 
56             // In this sample, it's enough of a callback URL match if the scheme and host match.
57             // In a production app, it is advisable to require a match on the path as well.
58             Uri acceptableCallbackPattern = new Uri(this.Callback);
59             if (string.Equals(acceptableCallbackPattern.GetLeftPart(UriPartial.Authority), callback.GetLeftPart(UriPartial.Authority), StringComparison.Ordinal))
60             {
61                 return true;
62             }
63 
64             return false;
65         }
66 
67 
68         bool IClientDescription.IsValidClientSecret(string secret)
69         {
70             return MessagingUtilities.EqualsConstantTime(secret, this.ClientSecret);
71         }
72 
73 
74     }
75 }

3、实现IAuthorizationServerHost接口

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Security.Cryptography;
 5 using System.Web;
 6 using DotNetOpenAuth.Messaging.Bindings;
 7 using DotNetOpenAuth.OAuth2;
 8 using DotNetOpenAuth.OAuth2.ChannelElements;
 9 using DotNetOpenAuth.OAuth2.Messages;
10 
11 namespace IdefavAuthorizationServer.Code
12 {
13     public class IdefavAuthorizationServerHost : IAuthorizationServerHost
14     {
15         /// <summary>
16         /// 配置
17         /// </summary>
18         private readonly AuthorizationServerConfiguration _configuration;
19 
20         /// <summary>
21         /// 构造函数
22         /// </summary>
23         /// <param name="config"></param>
24         public IdefavAuthorizationServerHost(AuthorizationServerConfiguration config)
25         {
26             if (config != null)
27                 _configuration = config;
28         }
29 
30         /// <summary>
31         /// Token创建
32         /// </summary>
33         /// <param name="accessTokenRequestMessage"></param>
34         /// <returns></returns>
35         public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage)
36         {
37             var accessToken = new AuthorizationServerAccessToken();
38             accessToken.Lifetime = _configuration.TokenLifetime;//设置Token的有效时间
39 
40             // 设置加密公钥
41             accessToken.ResourceServerEncryptionKey =
42                 (RSACryptoServiceProvider)_configuration.EncryptionCertificate.PublicKey.Key;
43             // 设置签名私钥
44             accessToken.AccessTokenSigningKey = (RSACryptoServiceProvider)_configuration.SigningCertificate.PrivateKey;
45 
46             var result = new AccessTokenResult(accessToken);
47             return result;
48         }
49 
50         public IClientDescription GetClient(string clientIdentifier)
51         {
52             // 这里需要去验证客户端发送过来的client_id
53             if (string.Equals(clientIdentifier, "idefav", StringComparison.CurrentCulture))// 这里为了简明起见没有使用数据库
54             {
55                 var client=new Client
56                 {
57                     Name = "idefav",
58                     ClientSecret = "1",
59                     ClientType = 1
60                 };
61                 return client;
62             }
63             throw new ArgumentOutOfRangeException("clientIdentifier");
64         }
65 
66         public bool IsAuthorizationValid(IAuthorizationDescription authorization)
67         {
68             return true;
69         }
70 
71         public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant(string userName, string password,
72             IAccessTokenRequest accessRequest)
73         {
74             throw new NotImplementedException();
75         }
76 
77         public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest)
78         {
79             AutomatedUserAuthorizationCheckResponse response = new AutomatedUserAuthorizationCheckResponse(accessRequest, true, "test");
80             return response;
81         }
82 
83         public ICryptoKeyStore CryptoKeyStore { get; }
84         public INonceStore NonceStore { get; }
85 
86        
87     }
88 }

4、实现OAuthController

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using System.Web;
 6 using System.Web.Mvc;
 7 using DotNetOpenAuth.Messaging;
 8 using DotNetOpenAuth.OAuth2;
 9 using IdefavAuthorizationServer.Code;
10 
11 namespace IdefavAuthorizationServer.Controllers
12 {
13     public class OAuthController : Controller
14     {
15         private readonly AuthorizationServer authorizationServer =
16            new AuthorizationServer(new IdefavAuthorizationServerHost(Common.Configuration));
17 
18         public async Task<ActionResult> Token()
19         {
20             var response = await authorizationServer.HandleTokenRequestAsync(Request);
21             return response.AsActionResult();
22         }
23     }
24 }

5、初始化AuthorizationServerConfiguration

这里采用Windows签名证书

放到项目中

制作证书事注意:要加上-a sha1  -sky exchange

 

到此,基本代码就写完了,现在说说要注意的地方,OAuth2默认设置的请求是要求SSL的也就是必须是https//localhost:1111/OAuth/Token,然后我们现在不需要使用SSL加密请求,更改一下WebConfig文件

在WebConfig里面设置成如图中那样,就可以不用https访问了

 

6、我们F5运行项目

使用Post工具发送Post请求访问 http://localhost:53022/OAuth/token 

Body参数:

1 client_id:idefav
2 client_secret:1
3 grant_type:client_credentials

请求结果:

 

这样我们就拿到了access_token,通过这个access_token我们就可以访问资源服务器了

 

 

 

更新:

OAuthController代码添加内容类型

 1 using System.Collections.Generic;
 2 using System.Linq;
 3 using System.Threading.Tasks;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 using System.Web.Script.Services;
 7 using DotNetOpenAuth.Messaging;
 8 using DotNetOpenAuth.OAuth2;
 9 using IdefavAuthorizationServer.Code;
10 
11 namespace IdefavAuthorizationServer.Controllers
12 {
13     public class OAuthController : Controller
14     {
15         private readonly AuthorizationServer authorizationServer =
16            new AuthorizationServer(new IdefavAuthorizationServerHost(Common.Configuration));
17         
18         public async Task<ActionResult> Token()
19         {
20             var response = await authorizationServer.HandleTokenRequestAsync(Request);
21             Response.ContentType = response.Content.Headers.ContentType.ToString();
22             return response.AsActionResult();
23         }
24     }
25 }

 

鉴于有人不知道Windows签名制作,下篇我们一起来看看如何制作一个认证服务器可以使用的签名证书

转载于:https://www.cnblogs.com/idefav2010/p/DotNetOpenAuth.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/358143.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

使用可选是可选的

在上周的“收藏中的可选内容”一文发表之后&#xff0c;我不禁要多讲一些关于同一只野兽的事情。 更多细节。 最初由Google Guava引入并后来包含在Java 8软件包中的Optionial类只是包装可选对象的包装器。 从包装对象存在或包装中没有对象的意义上讲&#xff0c;包装对象是可选…

kali 清理系统垃圾文件

网上常用的shell命令 #!/bin/bash echo "clear temp file..." sudo apt-get autoclean # 清理旧版本的软件缓存 sudo apt-get clean # 清理所有软件缓存 sudo apt-get autoremove # 删除系统不再使用的孤立软件 echo "clear disk temp..." sync  #…

PDF如何XSS

简介 在上传点时&#xff0c;如果上传不了图片格式的文件&#xff0c;可以尝试上传html或者pdf文件来达到xss的效果。上传html就不多说了&#xff0c;下面来说说怎么让pdf弹窗。 操作步骤&#xff1a; 环境准备&#xff1a;python3 需要准备poc.py和poc.js poc.py内容 # FRO…

NOI 练手题 图像旋转翻转变换

题目&#xff1a;来源http://noi.openjudge.cn/ch0112/09/ 总时间限制: 1000ms内存限制: 65536kB描述给定m行n列的图像各像素点灰度值&#xff0c;对其依次进行一系列操作后&#xff0c;求最终图像。 其中&#xff0c;可能的操作及对应字符有如下四种&#xff1a; A&#xff1a…

CSDN Chrome插件来啦,听说可以提升开发者效率,我们先来研究一波

孙叫兽,安徽宿州人,北漂前端全栈程序员(朝着这个目标努力),如果你觉得这篇文章帮助了你,记得三连👉(转发+点赞+评论),技术交流请联系个人主页左侧导航栏。 这个插件的定位是提升程序员的开发效率的,至于哪方面?自己慢慢体会,我大致的感觉就是搜索引擎的导航网站的…

C盘全面清理教程!彻底清理所有垃圾!

预计阅读时间 10分钟 资源在文末获取哦 老懒粉应该知道&#xff0c;我们写过“宇宙最细”的系统安装/重装教程 但我们除了新机&#xff0c;通常情况下重装系统的目的是什么&#xff1f; 虽然不管电脑出现了什么样的软件方面问题&#xff0c;我们都可以通过重装系统来一劳永…

python常用类型的内置函数列表

1、list.append(obj) 向列表中加入一个对象obj fruits [apple, pear, orange] >>> fruits.append(apple) >>> fruits [apple, pear, orange, apple]2、list.count(obj) 返回一个对象obj在列表中出现的次数 >>> fruits.count(a…

java虚拟内存扩展_Java 8虚拟扩展方法

java虚拟内存扩展我一直关注Java 8 Lambda表达式项目的发展已经有一段时间了&#xff0c;我对其当前的进展状态感到非常兴奋。 我发现的最新“易于理解”的演示文稿是这样的&#xff1a; http://blogs.oracle.com/briangoetz/resource/devoxx-lang-lib-vm-co-evol.pdf 现在&…

url重定向绕过方式

url重定向绕过方式 俗话说的好&#xff0c;上有政策&#xff0c;下有对策&#xff0c;url重定向的绕过姿势也越来越多样化。普通url重定向方法测试不成功&#xff0c;换个姿势&#xff0c;说不定可以再次绕过。 这里总结下成功的绕过方式。 &#xff08;1&#xff09; 使用…

【转】android:DDMS查看Threads--不错

原文网址&#xff1a;http://www.cnblogs.com/mybkn/archive/2012/05/27/2520335.html 有时候程序运行出现死锁或者信号量卡死是很纠结的问题&#xff0c;单看代码很难分析定位问题&#xff0c;这时候可以借助DDMS来查看threads的运行情况&#xff0c;一目了然。 手机连接上USB…

史上最全的技术手册整理总结,编程小白都从这篇文章迅速成为大牛

孙叫兽,前端全栈攻城狮,更多资源请关注微信公众号:电商程序员 整理云端的开发,助你开发效率与认知起码提升十倍。 技术手册 Python初级手册Python进阶手册Python2手册Python3手册HTML手册CSS手册CSS3手册HTML5手册Boostrap4手册Boostrap3手册Boostrap手册

并发最佳实践

本文是我们名为“ 高级Java ”的学院课程的一部分。 本课程旨在帮助您最有效地使用Java。 它讨论了高级主题&#xff0c;包括对象创建&#xff0c;并发&#xff0c;序列化&#xff0c;反射等。 它将指导您完成Java掌握的过程&#xff01; 在这里查看 &#xff01; 目录 1.简…

Fastjson反序列化漏洞复现(实战案例)

漏洞介绍 FastJson在解析json的过程中&#xff0c;支持使用autoType来实例化某一个具体的类&#xff0c;并调用该类的set/get方法来访问属性。通过查找代码中相关的方法&#xff0c;即可构造出一些恶意利用链。 通俗理解就是&#xff1a;漏洞利用fastjson autotype在处理json对…

SVN Error: Can‘t connect to host xxxxx‘: 由于目标计算机积极拒绝,无法连接,的最快解决办法

孙叫兽&#xff0c;前端全栈&#xff0c;微信公众号&#xff1a;电商程序员。如果本文对你有帮助&#xff0c;记得点赞关注&#xff0c;谢谢&#xff01; 每次换个新电脑&#xff0c;新项目&#xff0c;新场地&#xff0c;新公司都有可能使用SVN下载老项目,有的是用内网&#x…

夺命雷公狗---无限级分类NO3

<?phpheader("Content-Type:text/html;charsetutf-8");/*无限级分类。牵扯2个应用0是-找指定栏目的子栏目1是-找指定栏目的子孙栏目&#xff0c;即子孙树2是-找指定栏目的父栏目/父父栏目....顶级栏目&#xff0c;即家谱树*/$aarr array(array(id>1,name>…

百度地图接口调用

当我们网站需要调用百度地图接口的时候&#xff0c;可以使用如下方法&#xff1a; 1.如何获取经纬度坐标 1.打开百度地图&#xff0c;在百度地图最底部找到“地图开放平台”链接。 2.进入“百度地图开放平台”网站中&#xff0c;在导航中选择“”开发文档>坐标拾取器“”…

java后端工程师平时开发或多或少会用到eclipse,那么它有哪些快捷键呢

孙叫兽&#xff0c;前端全栈工程师&#xff0c;微信公众号&#xff1a;电商程序员&#xff0c;主页QQ群有eclipse安装包。 下载地址&#xff1a;https://www.eclipse.org/downloads/ Eclipse 是一个开放源代码的、基于Java的可扩展开发平台。就其本身而言&#xff0c;它只是一个…

信息安全系统设计基础第六周学习总结

第六章 存储器层次结构 存储器系统 是一个具有不同容量、成本和访问时间的存储设备的层次结构。 1.CPU寄存器&#xff1a;容量小&#xff0c;成本高&#xff0c;访问快 2.高速缓存存储器&#xff1a;CPU和主存之间的缓存区域 3.主存&#xff1a;磁盘上大容量&#xff0c;成本低…

phpStudy + PhpStorm + XDebug调试【绝对能用】

具体参照的是这篇文章&#xff1a;https://blog.csdn.net/weixin_40418199/article/details/79088365 文章有些地方说的不是很详细想重写整理下。 【PHPStudy演示的版本为&#xff1a;PHP5.4.45-Apache】 1.PHPStudy配置 PHPStudy自带了XDebug的扩展&#xff0c;不需要下载 php…

亚马逊标题自动抓取_15分钟内开始使用Amazon Web Services和全自动资源调配

亚马逊标题自动抓取在等待一个新项目时&#xff0c;我想学习一些有用的东西。 而且由于在许多项目中我们需要评估和测试正在开发的应用程序的性能&#xff0c;而很少有足够的硬件来生成实际负载&#xff0c;因此我决定学习更多有关按需在云中按需配置虚拟机的知识&#xff0c;即…