5- ASP.NET Core 2.1 InMemoryIden

2018-07-28  本文已影响97人  俊果果

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 的一种实现】

3. Oauth2 Flows

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


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


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


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

4. github code

上一篇 下一篇

猜你喜欢

热点阅读