OIDC – OpenIddict Core

3 选 1

IdentityServer 4

本来 IdentityServer 4 一直都是首选的, 但在 2020 年他们决定成立公司, IdentityServer 5 就开始收费了.

The Future of IdentityServer

 

Azure Active Directory B2C

Azure 的 SASS

ASP.NET Core 6 and Authentication Servers

ASP.NET Core Team 明确表示他们不会投入任何资源去研发类似 IdentityServer 的东西, 虽然 ASP.NET Core 5.0 开始, SPA 的 template 是依赖 IdentityServer 4 的,

并且 6.0 也会依赖, 7.0 会有替代, 但绝对没有计划要做类似的或者辅助类似的 Library, 原因是 M$ 要卖 Azure 产品.

 

OpenIddict Core 

Github 地址

这个是目前跟 IdentityServer 4 最靠近的替代库了. 这篇主要介绍这个

关于这 3 者的对比可以参考 : 

Token-Based Security: 3 Possible Alternatives To IdentityServer

ASP.NET Core 6 and authentication servers: the real bait and switch is not the one you think (OpenIddict Core 作者写的)

 

前言

OpenIddict 是很小的项目, 算是 1 个人维护的吧 (不过作者也挺厉害的, 一直用心维护着) 

它没有 IdentityServer 那么好的封装, 文档, 教程. 但是对于开发人员来说, 要搞起来还是挺容易的. 

这里只是大概记入一些 OpenIddict 对应的关系和解释, 并不会 step by step 的教, 要整个搞起来建议跟着 refer 做.

 

主要参考:

Step by step tutorial (client = Postman) 

Step by step tutorial (client = Angular)

项目源码 

官网文档

各种 Samples 

Config 的一些细节

 

Startup.cs 说起

OpenIddict 推荐使用 EF Core 做 (好像是可以换 Storage, 但我就是用 EF Core 的所以也没有去研究其它的)

使用 UseOpenIddict extension 来进行 setup 

这里和 IdentityServer 4 的 setup 方式不太一样哦. Library 如果要结合 EF Core 的话, 我目前觉得 IdentityServer 4 的方式会比较正确. 就是使用分开的 Context Migrations 

OpenIddict 用的方式是 ReplaceService

通过 ReplaceService, OpenIddict 就可以拦截到 EntityModelBuilder

不过有一点要注意哦, ReplaceService 只能调用一次而已. 如果项目本身有用到或者其它 Library 也有用到, 是会坏掉的. 所以我还是觉得 Library 应该要向 IdentityServer 4 那样,使用不同的 DbContext 来管理. 

接下来就是 AddOpenIddict()

AddQuartz 是因为 OpenIddict 需要定时去 Database 清楚过期的 Access Token, 所以需要依赖一个 Server Task Library, 而它选了 Quartz ... 竟然不选 Hangfire...

然后是 .AddCore 负责 setup EF Core 和 Quartz

接着是 .AddServer 就是 autho server 的主要 config 了

里面有: 

Token 的寿命 

支持的 Flow 

各种 Endpoint URL

签名用到的钥匙 (非对称加密 X.509).

如果想从 Azure Key Vault 拿 certificate 不能使用 Async 哦.

OpenIddict 作者的回复: Make the ConfigureServices method async in Startup.cs

Token 加密用到的钥匙 (我目前 autho 和 resource server 是同一台, 所以这里我选择用对称加密, 一把钥匙就好了, 如果是分开的情况那么 autho server 就要有 resource server 的公钥, 之前的文章有讲过)

它的钥匙也是支持 key rotation 的, 和 IdentityServer 类似. 你放多多把钥匙进去, 它选来用

最后的 UseDataProtection 是指 access token, refresh token 的加密, identity token 只能用 JWT 哦. (我看官网好像是推荐使用 Data Protection, 我觉得也挺好的, 毕竟 Identity Cookie 也是用 Data Protection)

接下来是 resource server 的 config (我的 autho 和 resource 是同一台, 所以是在一起 setup)

UseLocalServer 是因为我的 autho 和 resource 是同一台, 如果是分开的话, resource server 需要验证签名, 所以还需要 link 去 autho discover 发现 server 的公钥. 

同时解密 Token 也是需要 config 钥匙.

然后是 add test data, 这里的 test data 是指 client infomation

production 的情况下, client 数据 should be 已经在数据库里面了.

在来看看 client 是怎样输入的

 更新 2021-12-15: 补上很重要的 Logout

这里用 Insomnia (类似 Postman) 来做测试 

上半段注释掉的是 for client credentials flow 的, 下面是 authorization code flow + PKCE(前后端分离 web app 的 flow)

Insomnia.rest 是 client redirect URL, 

scope API 就是 resource server

openid 是要求返回 identity token 

offline_access 就是返回 refresh token 

具体测试画面长这样

setting 关掉 validate certificates (因为本地测试使用 self signed certificate)

不关掉会有 error

PKCE 不需要 client secret 但需要 code_verifier 和 code_challenge. (Insomnia 内置了)

所有的 token endpoint 我们需要自己做 (IdentityServer 4 是有封装的, OpenIddict 没有)

 View Code

注意: Authen server connect/userinfo 是用· 

[Authorize(AuthenticationSchemes = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)]

最后是 resource server 的 api, 大概长这样. 

注意: Resource server 的 API 用的是 OpenIddictValidationAspNetCoreDefaults 和 Authen Server 的 OpenIddictServerAspNetCoreDefaults 是不同的哦.

[Authorize(AuthenticationSchemes = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme)]

出错放错了会报错: 

An identity cannot be extracted from this request.
This generally indicates that the OpenIddict server stack was asked to validate a token for an endpoint it doesn't manage.
To validate tokens received by custom API endpoints, the OpenIddict validation handler

后端的部分大概就是这样了. 可以看出来上面这些只是 simple play around 而已.

要在项目上真的跑起来的话, 还需要搞定 : 

1. client 进数据库

2. 证书 X.509

3. 登入页面和同意 (consent) 页面, assign claims

 

前端部分 Javascript

IdentityServer 4 有封装 coidc-client.js 的, 而 OpenIddict 自然是没有咯.

上面的例子都是使用了 Insomnia or Postman, 这里说一下 js 实现的话需要注意的几个点.

流程可以看这篇 oAuth2.0 简介 - 移动端app,

首先是 endpoint discovery well-known

然后 redirect to login

然后 callback 页面 ajax post 去拿 access token

Content-Type 是 application/x-www-form-urlencoded 哦.

code_verifier 和 code_challenge

要完成这 2 个, 需要 random string (不可以用 Math.random, 不够安全, C# 也是不可以哦), SHA256, Base64URL-encoded. 

在 node.js 是有 build-in 支持这些的

code_verifier: 

code_challenge:

但是在 browser 却没有..., 使用 crypto-js 会导致 size 很大 . 所以比较好的方式是用 browser build-in 的接口,

参考:

Generate code_verifier and code_challenge in IE11 and modern browsers

Generating the code challenge for PKCEin OAuth 2

Proof Key for Code Exchange (PKCE)

Creating a code verifier and challenge for PKCEauth on Spotify API in ReactJS

How to calculate PCKE's code_verifier?

oauth-pkce

太多种版本了... 但核心是差不多的. 

js 做 random string 需要用到 window.crypto.getRandomValues

它是这样子用的

let array1 = new Uint8Array(1);
let array2 = new Uint16Array(1);
let array3 = new Uint32Array(1);
array1 = window.crypto.getRandomValues(array1); // { 0: 168 } 
array2 = window.crypto.getRandomValues(array2); // { 0: 64634 }
array3 = window.crypto.getRandomValues(array3); // { 0: 2577571238 }

开一个 UintArray (8, 16, 32) 都可以, 调用 getRandom 后 array 里面就有 number. 依据 8, 16, 32 number 会不同长度. 

如果 new UintArray(10) 则会有 0 到 10 的 property 咯. 

有了 random number, 下一步就是把它弄成 random string. 做法很多, 比如可以写 abc...zAbc...Z1234...0, 然后 for loop 刚才的 random number 去抽 string 出来

也可以把 number toString(16) 变成 16 进制, 关键就是让这个 string 多样化一点, 到足够的 length 就可以停了. 

接下来就是做 SHA256, 用到 window.crypto.subtle.digest

private sha256Async(codeVerifier: string): Promise<ArrayBuffer> {
  const encoder = new TextEncoder();
  const data = encoder.encode(codeVerifier);
  return window.crypto.subtle.digest('SHA-256', data);
}

它返回的是 ArrayBuffer.

最后是 convert to Base64 URL encode

复制代码
private base64UrlEncode(value: ArrayBuffer): string {
  return window
    .btoa(String.fromCharCode.apply(null, Array.from(new Uint8Array(value))))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');
}
复制代码

题外话: JS UUID

参考: YouTube – Stop Using The uuid Library In JavaScript

crypto 除了可以生成 random 还可以做 uuid 哦

console.log(crypto.randomUUID()); // bf28ef0b-765b-4174-8e9b-5e7ef5a1d213

支持率很好

state

state 也是要用安全的 random string, 然后一定要对比, 确保 handle code 收到的 state 是之前发出去的. 

Angular 简单实现

参考: IMPLEMENTING OPENID CODE FLOW WITH PKCEUSING OpenIddict AND ANGULAR

app.ts

 View Code

callback.ts

 View Code

logout 是用 form post 而不是 ajax.

复制代码
<form method="post" action="https://192.168.1.152:44300/connect/logout">
  <input
    type="hidden"
    name="post_logout_redirect_uri"
    value="https://192.168.1.152:4200/signout-oidc"
  />
  <button>LOGOUT</button>
</form>
复制代码
转 https://www.cnblogs.com/keatkeat/p/14952646.html
posted @ 2023-01-06 09:09  dreamw  阅读(729)  评论(0编辑  收藏  举报