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
这里的配置是为了添加方便管理,其实可以不用这个类
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();
} /// <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 = "",
ClientType =
};
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参数:
client_id:idefav
client_secret:
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();
}
}
}
鉴于有人不知道Windows签名制作,下篇我们一起来看看如何制作一个认证服务器可以使用的签名证书
DotNetOpenAuth实践之搭建验证服务器的更多相关文章
- DotNetOpenAuth实践之WebApi资源服务器
系列目录: DotNetOpenAuth实践系列(源码在这里) 上篇我们讲到WCF服务作为资源服务器接口提供数据服务,那么这篇我们介绍WebApi作为资源服务器,下面开始: 一.环境搭建 1.新建We ...
- DotNetOpenAuth实践
DotNetOpenAuth实践之搭建验证服务器 DotNetOpenAuth是OAuth2的.net版本,利用DotNetOpenAuth我们可以轻松的搭建OAuth2验证服务器,不废话,下面我们来 ...
- DotNetOpenAuth Part 1 : Authorization 验证服务实现及关键源码解析
DotNetOpenAuth 是 .Net 环境下OAuth 开源实现框架.基于此,可以方便的实现 OAuth 验证(Authorization)服务.资源(Resource)服务.针对 DotNet ...
- DotNetOpenAuth实践系列
写在前面 本人在研究DotNetOpenAuth的过程中,遇到很多问题,很多坑,花费了很多时间才调通这玩意,现在毫无保留的分享出来,希望博友们可以轻松的上手DotNetOpenAuth,减少爬坑时间. ...
- 用 Apache James 搭建邮件服务器来收发邮件实践(一)(转)
Apache James 简称 James, 是 Java Apache Mail Enterprise Server的缩写.James 是100%基于Java的电子邮件服务器.它是一种独立的邮件服务 ...
- 信安实践——自建CA证书搭建https服务器
1.理论知识 https简介 HTTPS(全称:Hyper Text Transfer Protocol over Secure Socket Layer),是以安全为目标的HTTP通道,简单讲是HT ...
- .net core 3.0 搭建 IdentityServer4 验证服务器
叙述 最近在搞 IdentityServer4 API接口认证部分,由于之前没有接触过 IdentityServer4 于是在网上一顿搜搜搜,由于自己技术水平也有限,看了好几篇文章才搞懂,想通过博客 ...
- DotNetOpenAuth实践之WCF资源服务器配置
系列目录: DotNetOpenAuth实践系列(源码在这里) 上一篇我们写了一个OAuth2的认证服务器,我们也获取到access_token,那么这个token怎么使用呢,我们现在就来揭开 一般获 ...
- DotNetOpenAuth实践之Windows签名制作
系列目录: DotNetOpenAuth实践系列(源码在这里) 在上篇中我们搭建了一个简单的认证服务器,里面使用到了Windows签名证书,这一篇则是教大家如何制作Windows签名证书,下面进入正题 ...
随机推荐
- scrum敏捷开发重点介绍
参考: http://www.scrumcn.com/agile/scrum-knowledge-library/scrum.html https://www.zhihu.com/question/3 ...
- 如何使用vuejs过滤器
大家再使用vue做项目时,查询功能当然必不可少,这就得使用vue强大的filter啦.其实vue内置的两个属性filterBy和orderBy已经能满足部分需求了,但是她更大的的魅力在于自定义filt ...
- Centos7远程桌面 vnc/vnc-server的设置
Centos7与Centos6.x有了很大的不同. 为了给一台服务器装上远程桌面,走了不少弯路.写这篇博文,纯粹为了记录,以后如果遇到相同问题,可以追溯. 1.假定你的系统没有安装vnc的任何软件,那 ...
- Java入门系列(四)内部类
为什么需要内部类? 真正的原因是这样的,java中的内部类和接口加在一起,可以的解决常被C++程序员抱怨java中存在的一个问题没有多继承.实际上,C++的多继承设计起来很复杂,而java通过内部类加 ...
- c++刷题(21/100)树的打印、矩阵覆盖和括号生成
题目一:把二叉树打印成多行 从上到下按层打印二叉树,同一层结点从左至右输出.每一层输出一行. 思路:一开始以为2维的vector可以直接访问,但是试了是不行,会报错,vector在有值之前不能直接访问 ...
- 【leetcode 简单】 第五十八题 计数质数
统计所有小于非负整数 n 的质数的数量. 示例: 输入: 10 输出: 4 解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 . class Solution: def cou ...
- Python练习-os模块练习-还算是那么回事儿
# 编辑者:闫龙 # 小程序:根据用户输入选择可以完成以下功能: # 创建文件,如果路径不存在,创建文件夹后再创建文件 # 能够查看当前路径 # 在当前目录及其所有子目录下查找文件名包含指定字符串的文 ...
- C++的各种初始化方式
C++小实验测试:下面程序中main函数里a.a和b.b的输出值是多少? #include <iostream> struct foo { foo() = default; int a; ...
- 图片压缩之 PNG
作者:程志达链接:https://zhuanlan.zhihu.com/p/19570424来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. PNG(Portable N ...
- 2016.6.19——Length of Last Word
Length of Last Word 本题收获: 1.str.size()为负 2.size_t引发的死循环 3.题目思路,有时在写代码时很不清楚边界条件的输出值是什么,若为面试,一定要问清楚. 题 ...