教程集 www.jiaochengji.com
教程集 >  脚本编程  >  Asp.net  >  正文 DotNetOpenAuth搭建验证服务器及制作Windows签名

DotNetOpenAuth搭建验证服务器及制作Windows签名

发布时间:2016-11-27   编辑:jiaochengji.com
教程集为您提供DotNetOpenAuth搭建验证服务器及制作Windows签名等资源,欢迎您收藏本站,我们将为您提供最新的DotNetOpenAuth搭建验证服务器及制作Windows签名资源
DotNetOpenAuth是当前做得做好的基于.NET的OAuth开源实现,本文我们利用DotNetOpenAuth搭建OAuth2验证服务器,制作Windows签名。

DotNetOpenAuth搭建验证服务器

本次搭建环境:

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

一、环境搭建

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


<center></center>

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


<center></center>


<center></center>

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


<center></center>

输入DotNetOpenAuth 安装DotNetOpenAuth v5.0.0-alpha3


<center></center>

添加完成后


<center></center>

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

1、添加AuthorizationServerConfiguration.cs

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

<pre class="brush:c#;toolbar:false">using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Web; namespace IdefavAuthorizationServer.Code {     /// <summary>     /// 验证服务器配置     /// </summary>     public class AuthorizationServerConfiguration     {         /// <summary>         /// 构造函数         /// </summary>         public AuthorizationServerConfiguration()         {             TokenLifetime = TimeSpan.FromMinutes(5);         }         /// <summary>         /// 签名证书         /// </summary>         public X509Certificate2 SigningCertificate { get; set; }         /// <summary>         /// 加密证书         /// </summary>         public X509Certificate2 EncryptionCertificate { get; set; }         /// <summary>         /// Token有效时间         /// </summary>         public TimeSpan TokenLifetime { get; set; }     } }</pre>


2、实现IClientDescription接口

<pre class="brush:c#;toolbar:false">using System; using System.Collections.Generic; using System.Linq; using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2; namespace IdefavAuthorizationServer.Code {     public class Client : IClientDescription     {         /// <summary>         /// 客户端名称client_id         /// </summary>         public string Name { get; set; }         /// <summary>         /// 客户端类型         /// </summary>         public int ClientType { get; set; }         /// <summary>         /// 回调URL         /// </summary>         public string Callback { get; set; }         public string ClientSecret { get; set; }         Uri IClientDescription.DefaultCallback         {             get { return string.IsNullOrEmpty(this.Callback) ? null : new Uri(this.Callback); }         }         ClientType IClientDescription.ClientType         {             get { return (ClientType)this.ClientType; }         }         bool IClientDescription.HasNonEmptySecret         {             get { return !string.IsNullOrEmpty(this.ClientSecret); }         }         bool IClientDescription.IsCallbackAllowed(Uri callback)         {             if (string.IsNullOrEmpty(this.Callback))             {                 // No callback rules have been set up for this client.                 return true;             }             // In this sample, it's enough of a callback URL match if the scheme and host match.             // In a production app, it is advisable to require a match on the path as well.             Uri acceptableCallbackPattern = new Uri(this.Callback);             if (string.Equals(acceptableCallbackPattern.GetLeftPart(UriPartial.Authority), callback.GetLeftPart(UriPartial.Authority), StringComparison.Ordinal))             {                 return true;             }             return false;         }         bool IClientDescription.IsValidClientSecret(string secret)         {             return MessagingUtilities.EqualsConstantTime(secret, this.ClientSecret);         }     } }</pre>


3、实现IAuthorizationServerHost接口

<pre class="brush:c#;toolbar:false">using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Web; using DotNetOpenAuth.Messaging.Bindings; using DotNetOpenAuth.OAuth2; using DotNetOpenAuth.OAuth2.ChannelElements; using DotNetOpenAuth.OAuth2.Messages; namespace IdefavAuthorizationServer.Code {     public class IdefavAuthorizationServerHost : IAuthorizationServerHost     {         /// <summary>         /// 配置         /// </summary>         private readonly AuthorizationServerConfiguration _configuration;         /// <summary>         /// 构造函数         /// </summary>         /// <param name="config"></param>         public IdefavAuthorizationServerHost(AuthorizationServerConfiguration config)         {             if (config != null)                 _configuration = config;         }         /// <summary>         /// Token创建         /// </summary>         /// <param name="accessTokenRequestMessage"></param>         /// <returns></returns>         public AccessTokenResult CreateAccessToken(IAccessTokenRequest accessTokenRequestMessage)         {             var accessToken = new AuthorizationServerAccessToken();             accessToken.Lifetime = _configuration.TokenLifetime;//设置Token的有效时间             // 设置加密公钥             accessToken.ResourceServerEncryptionKey =                 (RSACryptoServiceProvider)_configuration.EncryptionCertificate.PublicKey.Key;             // 设置签名私钥             accessToken.AccessTokenSigningKey = (RSACryptoServiceProvider)_configuration.SigningCertificate.PrivateKey;             var result = new AccessTokenResult(accessToken);             return result;         }         public IClientDescription GetClient(string clientIdentifier)         {             // 这里需要去验证客户端发送过来的client_id             if (string.Equals(clientIdentifier, "idefav", StringComparison.CurrentCulture))// 这里为了简明起见没有使用数据库             {                 var client=new Client                 {                     Name = "idefav",                     ClientSecret = "1",                     ClientType = 1                 };                 return client;             }             throw new ArgumentOutOfRangeException("clientIdentifier");         }         public bool IsAuthorizationValid(IAuthorizationDescription authorization)         {             return true;         }         public AutomatedUserAuthorizationCheckResponse CheckAuthorizeResourceOwnerCredentialGrant(string userName, string password,             IAccessTokenRequest accessRequest)         {             throw new NotImplementedException();         }         public AutomatedAuthorizationCheckResponse CheckAuthorizeClientCredentialsGrant(IAccessTokenRequest accessRequest)         {             AutomatedUserAuthorizationCheckResponse response = new AutomatedUserAuthorizationCheckResponse(accessRequest, true, "test");             return response;         }         public ICryptoKeyStore CryptoKeyStore { get; }         public INonceStore NonceStore { get; }             } }</pre>


4、实现OAuthController

<pre class="brush:c#;toolbar:false">using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2; using IdefavAuthorizationServer.Code; namespace IdefavAuthorizationServer.Controllers {     public class OAuthController : Controller     {         private readonly AuthorizationServer authorizationServer =            new AuthorizationServer(new IdefavAuthorizationServerHost(Common.Configuration));         public async Task<ActionResult> Token()         {             var response = await authorizationServer.HandleTokenRequestAsync(Request);             return response.AsActionResult();         }     } }</pre>



5、初始化AuthorizationServerConfiguration

这里采用Windows签名证书


<center></center>

放到项目中


<center></center>

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

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


<center></center>

在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

请求结果:


<center></center>

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

更新:


OAuthController代码添加内容类型

<pre class="brush:c#;toolbar:false">using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Script.Services; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2; using IdefavAuthorizationServer.Code; namespace IdefavAuthorizationServer.Controllers {     public class OAuthController : Controller     {         private readonly AuthorizationServer authorizationServer =            new AuthorizationServer(new IdefavAuthorizationServerHost(Common.Configuration));                  public async Task<ActionResult> Token()         {             var response = await authorizationServer.HandleTokenRequestAsync(Request);             Response.ContentType = response.Content.Headers.ContentType.ToString();             return response.AsActionResult();         }     } }</pre>




DotNetOpenAuth制作Windows签名

一、工具

makecert.exe,cert2spc.exe,pvk2pfx.exe

百度网盘地址:

链接:http://pan.baidu.com/s/1ntOq3Cd 密码:j2rn

二、制作

1、创建一个自己签署的证书和一个私钥文件用到makecert工具

命令:

makecert -a sha1 -sky exchange -n "CN=发行者名称" -b 10/18/2015 -e 01/01/2018 -sv 你的名称.pvk 你的名称.cer

打开命令行,并定位到makecert.exe所在目录


<center></center>

输入命令

例如: makecert -a sha1 -sky exchange -n "CN=idefav" -b 10/18/2015 -e 01/01/2018 -sv test.pvk test.cer

回车之后,弹出私钥加密密码


<center></center>

输入密码后,目录里面就生成了cer和pvk文件


<center></center>

2、利用证书.cer创建发行者证书.spc,用到cert2spc工具

命令:

cert2spc 你的名称.cer 你的名称.spc

输入命令生成spc文件


<center></center>

3、从.pvk和.spc格式转换成.pfx格式,用到pvk2pfx工具

命令:

pvk2pfx -pvk 你的名称.pvk -pi pvk密码 -spc 你的名称.spc

注意:pvk密码就是上次弹出输入的密码

输入命令回车,弹出证书导出向导


<center></center>


<center></center>


<center></center>


<center></center>


<center></center>

这样cer和pfx就制作完成了,下面我们把这两个文件放到上篇制作的项目中去


<center></center>

改一下Global.axax中的初始化代码


<center></center>

运行项目使用post工具访问


<center></center>

成功获取access_token


您可能感兴趣的文章:
DotNetOpenAuth搭建验证服务器及制作Windows签名
Golang LicenseServer授权服务器的设计 与 RSA 密钥对的应用
php 服务器环境搭建配置(apache与iis两种方法)
(图)RHE5服务器配置-搭建Samba服务器
基于IIS的OTA无线游戏下载服务器配置[Everenter出品]
php服务器用什么系统
php网站用什么服务器
windows系统进程全攻略
搭建mysql数据库主主复制的教程(图文)
php服务器配置过程解析

[关闭]
~ ~