微软在 OWIN 框架中对 OAuth 认证的支持非常好, 使用现有的 OWIN 中间件可以做到:

微软提供了这么多的 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的更多相关文章

  1. SimpleSSO:使用Microsoft.Owin.Security.OAuth搭建OAuth2.0授权服务端

    目录 前言 OAuth2.0简介 授权模式 (SimpleSSO示例) 使用Microsoft.Owin.Security.SimpleSSO模拟OpenID认证 通过authorization co ...

  2. Microsoft.Owin.Security.OAuth搭建OAuth2.0授权服务端

    Microsoft.Owin.Security.OAuth搭建OAuth2.0授权服务端 目录 前言 OAuth2.0简介 授权模式 (SimpleSSO示例) 使用Microsoft.Owin.Se ...

  3. 无法安装程序包“MIcrosoft.Owin.Security 2.0.2”。您正在尝试将此程序包安装到某个将“.NETFramework,Version=v4.0”作为目标的项目中。

    在VS2010 MVC4项目中,安装NuGet程序包Microsoft.AspNet.SignalR时出现以下错误: 原因是安装的版本是Microsoft.AspNet.SignalR 2.0.2,要 ...

  4. 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 ...

  5. 无法解决“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的引用. 生成项目时," ...

  6. Microsoft.Owin.Hosting 实现启动webapp.dll

    Microsoft.Owin.Hosting 下面是 asp.net core 实现 using System;using System.Collections.Generic;using Syste ...

  7. Microsoft.SharePoint.Security的问题

    请求“Microsoft.SharePoint.Security.SharePointPermission, Microsoft.SharePoint.Security, Version=12.0.0 ...

  8. windows service承载的web api宿主搭建(Microsoft.Owin+service)

    今天突然想起改良一下以前搭建的“windows service承载的web api”服务,以前也是直接引用的类库,没有使用nuget包,时隔几年应该很旧版本了吧.所以本次把需要nuget获取的包记录一 ...

  9. Microsoft.Owin 使用 文件服务

    添加引用: <package id="Microsoft.Owin" version="4.0.1" targetFramework="net4 ...

随机推荐

  1. 732F Tourist Reform

    // CF 732F Tourist Reform // 思路:两遍tarjan // 找强联通分量 #include <bits/stdc++.h> using namespace st ...

  2. Gilde jar包冲突(环信的导入)

    Error:Execution failedfortask':app:transformClassesWithJarMergingForDebug'.>com.android.build.api ...

  3. leetcode 75 Sorted Colors

    两种解法 1)记录0和1的个数 然后按照记录的个数将0和1重新放入原数组,剩下的补2 2)双指针left,right left表示0~left-1都为0,即i之前都为0 right表示right+1~ ...

  4. 深入浅出 Java Concurrency (3): 原子操作 part 2[转]

    在这一部分开始讨论数组原子操作和一些其他的原子操作. AtomicIntegerArray/AtomicLongArray/AtomicReferenceArray的API类似,选择有代表性的Atom ...

  5. vue+element-ui 使用富文本编辑器

    npm安装编辑器组件npm install vue-quill-editor –save 在components文件夹创建ue.vue组件,如下 ue.vue代码如下: <!-- 组件代码如下 ...

  6. eureka添加security验证之后,client注册失败

    高版本,以下配置已弃用 security: basic: enabled: true 所以需要自定义security配置开启basic认证,参考我的配置类 @Configuration @Enable ...

  7. python-web-webbrower-beautifuSoup

    webbrowser:是 Python 自带的,打开浏览器获取指定页面. requests:从因特网上下载文件和网页. Beautiful Soup:解析 HTML,即网页编写的格式. seleniu ...

  8. shell中各种括号的作用详解()、(())、[]、[[]]、{}

    一.小括号,圆括号() 1.单小括号 () ①命令组.括号中的命令将会新开一个子shell顺序执行,所以括号中的变量不能够被脚本余下的部分使用.括号中多个命令之间用分号隔开,最后一个命令可以没有分号, ...

  9. (codeforces 853A)Planning 贪心

    Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n ...

  10. ubuntu setup.py 安装时报Error -5 while decompressing data: incomplete or truncated stream

    缺少 python-devel 包 apt-get install python-dev -y