扩展 Microsoft.Owin.Security
微软在 OWIN 框架中对 OAuth 认证的支持非常好, 使用现有的 OWIN 中间件可以做到:
- 使用 Microsoft.Owin.Security.OAuth 搭建自己的 OAuth2 服务端, 没做过的可以参考这个简单教程: 使用 OWIN 搭建 OAuth2 服务器 ;
- 使用 Microsoft.Owin.Security.Facebook 连接 Facbook 认证, 让用户使用 Facebook 帐户来登录;
- 使用 Microsoft.Owin.Security.Google 连接 Google 认证, 让用户使用 Google 帐户登录;
- 使用 Microsoft.Owin.Security.MicrosoftAccount 连接 Microsoft 认证, 让用户使用 Microsoft 帐户登录;
- 使用 Microsoft.Owin.Security.Twitter 连接 Twitter 认证, 让用户使用 Twitter 帐户登录;
微软提供了这么多的 OAuth 认证中间件, 对天朝的墙内用户来说, 只能用三个字来概括“然并卵”。
要接入国内 腾讯微信 、新浪微博提供的 OAuth2 认证, 还是要根据现有的中间件 Microsoft.Owin.Security 进行二次开发, 上面微软提供的 Facebook、 Google 等实现可以作为参考。
先来简单回顾一下 OAuth2 的 认证流程 , 如下图所示:

直接和 OAuth2 认证服务器交互的步骤有:
- (A) 将用户代理(浏览器)重定向到认证服务器, 需要提供客户端凭据 (Client Identifier) , 并取得认证码 (Authorization Code) ;
- (D) 使用认证服务器返回的认证码 (Authorization Code) 获取访问凭据 (Access Token) ;
- (E) 根据访问凭据 (Access Token) 获取用户信息。
Microsoft.Owin.Security 对这些步骤提供了优秀的扩展支持, 扩展步骤如下:
1、 创建自定义的 OAuth2AuthenticationOptions ,并继承自 Microsoft.Owin.Security.AuthenticationOptions , 代码如下:
public class OAuth2AuthenticationOptions : AuthenticationOptions {
// Client App Identifier
public string AppId { get; set; }
// Client App Secret
public string AppSecret { get; set; }
// The authorize url
public string AuthorizationEndpoint { get; set; }
// Token url
public string TokenEndpoint { get; set; }
// User info url
public string UserInformationEndpoint { get; set; }
}
2、 创建一个自定义的 Owin 中间件 OAuth2AuthenticationMiddleware , 并继承自 Microsoft.Owin.Security.AuthenticationMiddleware :
public class GdepAuthenticationMiddleware :
AuthenticationMiddleware<GdepAuthenticationOptions> { protected override AuthenticationHandler<OAuth2AuthenticationOptions> CreateHandler() {
return new OAuth2AuthenticationHandler(httpClient, logger);
} }
重写的基类的 CreateHandler 非常重要, 整个 OAuth2 认证的过程都会在这个方法创建的 AuthenticationHandler 实例中完成。
3、 接下来就是最重要的部分, OAuth2AuthenticationHandler 的实现了, 先来看一下基类 AuthenticationHandler , 实现它需要实现下面的几个方法:
public abstract class AuthenticationHandler {
protected abstract Task<AuthenticationTicket> AuthenticateCoreAsync ();
protected virtual Task ApplyResponseChallengeAsync () { }
public virtual Task<bool> InvokeAsync () { }
}
接下来分别说明一下这几个方法的作用:
在 ApplyResponseChallengeAsync 方法中响应 HTTP 401 Unauthorized , 将用户重定向到认证服务器, 即实现上面的步骤 (A) , 示例代码如下:
var authorizationEndpoint = Options.AuthorizationEndpoint +
"?response_type=code" +
"&client_id=" + Uri.EscapeDataString(Options.AppId) +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
"&scope=" + Uri.EscapeDataString(scope) +
"&state=" + Uri.EscapeDataString(state); var redirectContext = new GdepApplyRedirectContext(Context, Options, properties, authorizationEndpoint);
Options.Provider.ApplyRedirect(redirectContext);
在 AuthenticateCoreAsync 方法中根据认证服务器返回的认证码 (Authorization Code) 来获取用户信息, 示例代码如下:
var requestPrefix = Request.Scheme + "://" + Request.Host;
var redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath; var tokenRequest = new Dictionary<string, string> {
["grant_type"] = "authorization_code",
["code"] = code,
["redirect_uri"] = redirectUri,
["client_id"] = Options.AppId,
["client_secret"] = Options.AppSecret
};
var tokenResponse = await httpClient.PostAsync(
Options.TokenEndpoint,
new FormUrlEncodedContent(tokenRequest)
);
tokenResponse.EnsureSuccessStatusCode(); string json = await tokenResponse.Content.ReadAsStringAsync();
var form = JObject.Parse(json); var accessToken = form.Value<string>("access_token");
var expires = form.Value<string>("expires_in");
var tokenType = form.Value<string>("token_type");
var refreshToken = form.Value<string>("refresh_token"); string graphAddress = Options.UserInformationEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken);
if (Options.SendAppSecretProof) {
graphAddress += "&appsecret_proof=" + GenerateAppSecretProof(accessToken);
} var graphRequest = new HttpRequestMessage(HttpMethod.Get, graphAddress);
graphRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var graphResponse = await httpClient.SendAsync(graphRequest, Request.CallCancelled);
graphResponse.EnsureSuccessStatusCode();
json = await graphResponse.Content.ReadAsStringAsync();
JObject user = JObject.Parse(json);
在 InvokeReplyPathAsync 方法中用 SignInManager 登录, 然后返回给后续的应用程序 WebAPI 来处理, 示例代码如下:
var context = new GdepReturnEndpointContext(Context, ticker);
context.SignInAsAuthenticationType = Options.SignInAsAuthenticationType;
context.RedirectUri = ticker.Properties.RedirectUri; await Options.Provider.ReturnEndpoint(context); if (context.SignInAsAuthenticationType != null && context.Identity != null) {
var grantIdentity = context.Identity;
if (!string.Equals(grantIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal)) {
grantIdentity = new ClaimsIdentity(grantIdentity.Claims, context.SignInAsAuthenticationType, grantIdentity.NameClaimType, grantIdentity.RoleClaimType);
}
Context.Authentication.SignIn(context.Properties, grantIdentity);
}
到现在为止, 自定义的 OAuth2 认证中间件基本上就完成了, 代码量不算多, 如果有不清楚的地方, 可以参阅 katanaproject 的源代码。
扩展 Microsoft.Owin.Security的更多相关文章
- SimpleSSO:使用Microsoft.Owin.Security.OAuth搭建OAuth2.0授权服务端
目录 前言 OAuth2.0简介 授权模式 (SimpleSSO示例) 使用Microsoft.Owin.Security.SimpleSSO模拟OpenID认证 通过authorization co ...
- Microsoft.Owin.Security.OAuth搭建OAuth2.0授权服务端
Microsoft.Owin.Security.OAuth搭建OAuth2.0授权服务端 目录 前言 OAuth2.0简介 授权模式 (SimpleSSO示例) 使用Microsoft.Owin.Se ...
- 无法安装程序包“MIcrosoft.Owin.Security 2.0.2”。您正在尝试将此程序包安装到某个将“.NETFramework,Version=v4.0”作为目标的项目中。
在VS2010 MVC4项目中,安装NuGet程序包Microsoft.AspNet.SignalR时出现以下错误: 原因是安装的版本是Microsoft.AspNet.SignalR 2.0.2,要 ...
- OAuth Implementation for ASP.NET Web API using Microsoft Owin.
http://blog.geveo.com/OAuth-Implementation-for-WebAPI2 OAuth is an open standard for token based aut ...
- 无法解决“Microsoft.SharePoint.Security, Version=15.0.0.0,”与“Microsoft.SharePoint.Security, Version=14.0.0.0”之间的冲突
VisualStudio 2013创建控制台项目,.NetFramework选为4.5.生成目标平台:x64.然后添加对Microsoft.SharePoint.dll的引用. 生成项目时," ...
- Microsoft.Owin.Hosting 实现启动webapp.dll
Microsoft.Owin.Hosting 下面是 asp.net core 实现 using System;using System.Collections.Generic;using Syste ...
- Microsoft.SharePoint.Security的问题
请求“Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=12.0.0 ...
- windows service承载的web api宿主搭建(Microsoft.Owin+service)
今天突然想起改良一下以前搭建的“windows service承载的web api”服务,以前也是直接引用的类库,没有使用nuget包,时隔几年应该很旧版本了吧.所以本次把需要nuget获取的包记录一 ...
- Microsoft.Owin 使用 文件服务
添加引用: <package id="Microsoft.Owin" version="4.0.1" targetFramework="net4 ...
随机推荐
- Store工作原理
- 对json对象进行截取并按照某关键字进行排序
json对象截取后三个数据,并按照时间的顺序进行倒叙排序. var json = [{"sent_time":"08:29:09","dist&quo ...
- 19.10.14-Q
小$P$的咕事 总结: 还行,就是$T1$写的慢了,$T2,T3$暴力有点锅 T1 小模拟. 打就是了. 可以小小的手玩一下. (考试的时候某同志人肉对拍了$20min$)=.= 418 ms 360 ...
- typeof, offsetof, container_of宏
container_of宏实现如下: #define container_of(ptr, type, member) ({ \ )->member ) *__mptr = (ptr); \ (t ...
- dubbo入门学习(四)-----dubbo配置
配置来源 首先,从Dubbo支持的配置来源说起,默认有四种配置来源: JVM System Properties,-D参数 Externalized Configuration,外部化配置 Servi ...
- 基于PtrFrameLayout实现自定义仿京东下拉刷新控件
前言 最近基于项目需要,使用PtrFrameLayout框架实现了自定义的下拉刷新控件,大体效果类似于京东APP的下拉刷新动态效果.在这里和大家分享一下具体的思路和需要注意的地方,以便帮助有类似开发和 ...
- Harbor任意管理员注册漏洞复现
1. 简介 Harbor是一个用于存储和分发Docker镜像的企业级Registry服务器,通过添加一些企业必需的功能特性,例如安全.标识和管理等,扩展了开源Docker Distribution. ...
- JDK、Eclipse、Tomcat、Maven、IDEA 常见问题
windows操作分成了32位和64位的系统,不同的系统安装的软件也不一样. 查询电脑操作系统是多少位? J D K 01. 下载安装 02. 目录解释 03. 配置环境变量 (JDK安装成功后进行配 ...
- 使用C#反射实现用户控件调用父页面方法
using System.Reflection; MethodInfo mi = this.Page.GetType().GetMethod("GetUserName"); //该 ...
- Leetcode131. Palindrome Partitioning分割回文串
给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串. 返回 s 所有可能的分割方案. 示例: 输入: "aab" 输出: [ ["aa",&quo ...