5- ASP.NET Core 2.1 InMemoryIdentityServer example

1. UnitTest async method Example

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void Test()
        {
            Task.Run(async () => { await ClientCredentials_Test(); }).GetAwaiter().GetResult();
        }

        public async Task ClientCredentials_Test()
        {
            // call api
            var client = new HttpClient();
            var response = await client.GetAsync("http://localhost:53560/values");
            //Assert.IsTrue(response.IsSuccessStatusCode);   this will not pass
            var content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
            // DiscoveryClient need reference to nuget package [IdentityModel]
            // request token
            var disco = await DiscoveryClient.GetAsync("http://localhost:53560");
            var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
            var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1");

            Assert.IsFalse(tokenResponse.IsError);
            Console.WriteLine(tokenResponse.Json);

            // call api
            client = new HttpClient();
            client.SetBearerToken(tokenResponse.AccessToken);
            response = await client.GetAsync("http://localhost:53560/values");
            Assert.IsTrue(response.IsSuccessStatusCode);
            content = await response.Content.ReadAsStringAsync();
            Console.WriteLine(content);
        }
    }

2. Click Here 查看 Identity Server 4 with ASP.NET Core 2.0 的一个教程

术语定义【IdentityServer 是对 OAuth2 and OpenID 的一种实现】

  • User: Person using a Client and the owner of Protected Resource 使用客户端访问限制资源的用户
  • Client: The application that needs access to Protected Resource 需要访问限制资源的程序
  • Protected Resource: The resource being protected from unauthorised access (e.g. Web API) 限制访问的资源,例如 Web api 等
  • Server: Server that authorizes User and returns Access Tokens 提供用户验证和授权的服务器
  • Access Token: A secret key used to access Protected Resource 用来访问限制资源的密钥
  • Scopes: Values based on which access to Protected Resource features is limited 用来限制用户可以获取的资源范围【You can think about scopes as intent of the client, for example: The Client ask you to use your resource owner to grant me access to your openid scopes > given_name, email & prefered_username and your OAuth2 scope > WebApi.】
  • Redirect URI: Location where User returns after Auth. Server completes authorization 验证服务器完成授权后重定向到的位置
  • Client ID: Client’s identifier registered with the Auth. Server 客户端注册的id
  • Client Secret: Client’s secret registered with the Auth. Server. This must be kept confidential 客户端注册的密钥
    关于这方面的内容可以参考视频课程
  • Building and Securing a RESTful API for Multiple Clients in ASP.NET
  • OAuth2 and OpenID Connect Strategies for AngularJS and ASP.NET

3. Oauth2 Flows

这篇文章讲的比较好,参考下

  • Authorization Code Flow 此模式类似于平常网站看到的授权使用QQ、微信等登录方式
    1_ULF38OTiNJNQZ4lHQZqRwQ.png

    A client application :
    (a) makes an authorization request to an authorization endpoint,
    (b) receives a short-lived authorization code,
    (c) makes a token request to a token endpoint with the authorization code, and
    (d) gets an access token.

(a) User accesses the Client.
(b) User is redirected to Auth. Server.
(c) User provides username/password.
(d) User is redirected back to Client with a code.

Note: Code is exposed to the user.

(e) Client accesses the Auth. Server to exchange the code with an Access Token.

Note: Access Token is not exposed to the user.

(f) Client access the Protected Resource using the Access Token.

  • Implicit Flow 与上面类似,只不过没有了获取 authorization code 的步骤
    1__7h6INaOWSvRVzDKK5x9Zw.png

    A client application :
    (a) makes an authorization request to an authorization endpoint and
    (b) gets an access token directly from the authorization endpoint.

(a) User accesses the Client.
(b) User is redirected to Auth. Server.
(c) User provides username/password.
(d) User is redirected back to Client with an Access Token.

Note: Access Token is exposed to the user.

(e) Client access the Protected Resource using the Access Token.

  • Resource Owner Password Credentials Flow 直接在客户端输入用户名和密码,然后用用户名和密码去第三方服务器做验证,获取 access token
    1_UqiPF3HCsBU5IgCj1xV9dQ.png

    A client application :
    (a) makes a token request to a token endpoint and
    (b) gets an access token. In this flow, a client application accepts a user's ID and password although the primary purpose of OAuth 2.0 is to give limited permissions to a client application WITHOUT revealing the user's credentials to the client application.

(a) User accesses the Client and provides username/password.

Note: username/password is exposed to the Client.

(b) Client accesses the Auth. Server to exchange username/password with an Access Token.
(c) Client accesses the Protected Resource using the Access Token.

  • Client Credentials Flow 这个模式校验客户端,每个客户端有一个私有的id和secret,利用它们来获取 access token 再进行后续资源访问

    1_h5J_bXpLtqNg9zQ5JenIOQ.png

    A client application :
    (a) makes a token request to a token endpoint and
    (b) gets an access token. In this flow, user authentication is not performed and client application authentication only is performed.

  • Refresh Token Flow 在之前authorization request阶段会同时获取到 access token 和一个 refresh token,这里就可以利用 refresh token 重新获取一个 access token

    1_g2b5fpKje2piDKI4ZkW-4w.png

    A client application :
    (a) presents a refresh token to a token endpoint and
    (b) gets a new access token.

4. github code

  • CLICK HERE
  • 运行测试
    进入目录【Fiver.Security.AuthServer】,运行 dotnet run

    进入目录【Fiver.Security.AuthServer.Api】,运行 dotnet run
    20180729121719.png

    然后在 Visual Studio 中 debug 运行项目【Fiver.Security.AuthServer.Client】即可
    20180729121849.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,324评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,303评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,192评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,555评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,569评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,566评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,927评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,583评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,827评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,590评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,669评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,365评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,941评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,928评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,159评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,880评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,399评论 2 342

推荐阅读更多精彩内容