系列目录:

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实践之搭建验证服务器的更多相关文章

  1. DotNetOpenAuth实践之WebApi资源服务器

    系列目录: DotNetOpenAuth实践系列(源码在这里) 上篇我们讲到WCF服务作为资源服务器接口提供数据服务,那么这篇我们介绍WebApi作为资源服务器,下面开始: 一.环境搭建 1.新建We ...

  2. DotNetOpenAuth实践

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

  3. DotNetOpenAuth Part 1 : Authorization 验证服务实现及关键源码解析

    DotNetOpenAuth 是 .Net 环境下OAuth 开源实现框架.基于此,可以方便的实现 OAuth 验证(Authorization)服务.资源(Resource)服务.针对 DotNet ...

  4. DotNetOpenAuth实践系列

    写在前面 本人在研究DotNetOpenAuth的过程中,遇到很多问题,很多坑,花费了很多时间才调通这玩意,现在毫无保留的分享出来,希望博友们可以轻松的上手DotNetOpenAuth,减少爬坑时间. ...

  5. 用 Apache James 搭建邮件服务器来收发邮件实践(一)(转)

    Apache James 简称 James, 是 Java Apache Mail Enterprise Server的缩写.James 是100%基于Java的电子邮件服务器.它是一种独立的邮件服务 ...

  6. 信安实践——自建CA证书搭建https服务器

    1.理论知识 https简介 HTTPS(全称:Hyper Text Transfer Protocol over Secure Socket Layer),是以安全为目标的HTTP通道,简单讲是HT ...

  7. .net core 3.0 搭建 IdentityServer4 验证服务器

    叙述 最近在搞 IdentityServer4  API接口认证部分,由于之前没有接触过 IdentityServer4 于是在网上一顿搜搜搜,由于自己技术水平也有限,看了好几篇文章才搞懂,想通过博客 ...

  8. DotNetOpenAuth实践之WCF资源服务器配置

    系列目录: DotNetOpenAuth实践系列(源码在这里) 上一篇我们写了一个OAuth2的认证服务器,我们也获取到access_token,那么这个token怎么使用呢,我们现在就来揭开 一般获 ...

  9. DotNetOpenAuth实践之Windows签名制作

    系列目录: DotNetOpenAuth实践系列(源码在这里) 在上篇中我们搭建了一个简单的认证服务器,里面使用到了Windows签名证书,这一篇则是教大家如何制作Windows签名证书,下面进入正题 ...

随机推荐

  1. nltk_28Twitter情感分析模型

    sklearn实战-乳腺癌细胞数据挖掘(博客主亲自录制视频教程) https://study.163.com/course/introduction.htm?courseId=1005269003&a ...

  2. 疯狂Android讲义

    1 Android应用和开发环境2 Android应用的界面编程3 Android的事件处理4 Activity Fragment5 Intent IntentFilter6 Android应用的资源 ...

  3. Java基础-Calendar类常用方法介绍

    Java基础-Calendar类常用方法介绍 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.Calendar类概念 Calendar 类是一个抽象类,它为特定瞬间与一组诸如 Y ...

  4. 2017 10.25 NOIP模拟赛

    期望得分:100+40+100=240 实际得分:50+40+20=110 T1 start取了min没有用,w(゚Д゚)w    O(≧口≦)O T3 代码3个bug :数组开小了,一个细节没注意, ...

  5. jmeter上传图片附件-小插曲

    背景 最近,接到新项目的接口测试,发现该接口是需要上传图片,开始折腾了好久没有搞定,最后才发现st和sid,并不是作为请求实体,而是url的一部分,好吧,是我没有仔细 请求参数 { "con ...

  6. 新建springboot项目启动出错 Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

    错误信息入下: 2018-06-23 01:48:05.275 INFO 7104 --- [ main] o.apache.catalina.core.StandardService : Stopp ...

  7. Linux文件系统_每一个的意义

    2017年1月10日, 星期二 Linux文件系统_每一个的意义 rootfs: 根文件系统 FHS:Linux /boot: 系统启动相关的文件,如内核.initrd,以及grub(bootload ...

  8. Hive性能优化--map数和reduce数

    转自http://superlxw1234.iteye.com/blog/1582880 一.    控制hive任务中的map数:  1.    通常情况下,作业会通过input的目录产生一个或者多 ...

  9. Centos7系统中安装Nginx1.8.0

    Nginx的安装 tar -zxvf nginx-1.8.0.tar.gz cd nginx-1.8.0 ./configure make make install /usr/local/nginx/ ...

  10. 【我们开发有力量之二】利用javascript制作批量网络投票机器人(自动改IP)

    帮朋友忙网络投票,粗粗地看了下,投票没有什么限制,仅有一个ip校验:每天每个ip仅能投票一次. 也就是说,可以写一个程序,自动更换IP地址(伪造IP地址),实现批量刷票的目的.于是我写了一个投票机器人 ...