DotNetOpenAuth搭建验证服务器
本次搭建环境:
.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
这里的配置是为了添加方便管理,其实可以不用这个类
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; } } }
2、实现IClientDescription接口
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); } } }
3、实现IAuthorizationServerHost接口
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; } } }
4、实现OAuthController
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(); } } }
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代码添加内容类型
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(); } } }
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所在目录
输入命令
例如: makecert -a sha1 -sky exchange -n "CN=idefav" -b 10/18/2015 -e 01/01/2018
-sv test.pvk test.cer
回车之后,弹出私钥加密密码
输入密码后,目录里面就生成了cer和pvk文件
2、利用证书.cer创建发行者证书.spc,用到cert2spc工具
命令:
cert2spc 你的名称.cer 你的名称.spc
输入命令生成spc文件
3、从.pvk和.spc格式转换成.pfx格式,用到pvk2pfx工具
命令:
pvk2pfx -pvk 你的名称.pvk -pi pvk密码 -spc 你的名称.spc
注意:pvk密码就是上次弹出输入的密码
输入命令回车,弹出证书导出向导
这样cer和pfx就制作完成了,下面我们把这两个文件放到上篇制作的项目中去
改一下Global.axax中的初始化代码
运行项目使用post工具访问
成功获取access_token
以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索密码
, 服务器
, string
, new
, this
using
dotnetopenauth、dotnetopenauth实战、dotnetopenauth.core、dotnetopenauth sso、dotnetopenauth 官网,以便于您获取更多的相关知识。