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

更新时间:2020-03-12    来源:J2EE/EJB/服务器    手机版     字体:

【www.bbyears.com--J2EE/EJB/服务器】

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
{
    /// 
    /// 验证服务器配置
    /// 
    public class AuthorizationServerConfiguration
    {
        /// 
        /// 构造函数
        /// 
        public AuthorizationServerConfiguration()
        {
            TokenLifetime = TimeSpan.FromMinutes(5);
        }
        /// 
        /// 签名证书
        /// 
        public X509Certificate2 SigningCertificate { get; set; }
        /// 
        /// 加密证书
        /// 
        public X509Certificate2 EncryptionCertificate { get; set; }
        /// 
        /// Token有效时间
        /// 
        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
    {
        /// 
        /// 客户端名称client_id
        /// 
        public string Name { get; set; }
        /// 
        /// 客户端类型
        /// 
        public int ClientType { get; set; }
        /// 
        /// 回调URL
        /// 
        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
    {
        /// 
        /// 配置
        /// 
        private readonly AuthorizationServerConfiguration _configuration;
        /// 
        /// 构造函数
        /// 
        /// 
        public IdefavAuthorizationServerHost(AuthorizationServerConfiguration config)
        {
            if (config != null)
                _configuration = config;
        }
        /// 
        /// Token创建
        /// 
        /// 
        /// 
        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 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 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


本文来源:http://www.bbyears.com/jsp/86527.html