ASP.NET Core分布式项目实战(oauth密码模式identity server4实现)

任务12:oauth密码模式identity server4实现

密码模式比客户端模式更加严格,需要第三方输入用户名和密码之后才可以访问 API

在 IdentityServerCenter 的 Config 中引入测试命名空间

using IdentityServer4.Test;

并添加一个获取 TestUser 的方法

public static List<TestUser> GetTestUsers()
{
    return new List<TestUser>
    {
        new TestUser
        {
            SubjectId = "1",
            Username = "mingsonzheng",
            Password = "123456"
        }
    };
}

正式环境的话从数据库读取

client 列表中复制添加一个 client,修改 ClientId 和 AllowedGrantTypes

new Client()
{
    ClientId = "pwdclient",
    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
    ClientSecrets =
    {
        new Secret("secret".Sha256())
    },
    AllowedScopes = {"api"},
}

在 Startup 中 AddTestUsers

services.AddIdentityServer()
        .AddDeveloperSigningCredential()
        .AddInMemoryApiResources(Config.GetResource())
        .AddInMemoryClients(Config.GetClients())
        .AddTestUsers(Config.GetTestUsers());

启动 IdentityServerCenter 与 ClientCredentialApi

获取 access_token

ASP.NET Core分布式项目实战(oauth密码模式identity server4实现)

在 config 中可以通过修改配置 RequireClientSecret,使得调用接口不需要传参 client_secret

new Client()
{
    ClientId = "pwdClient",
    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
    ClientSecrets =
    {
        new Secret("secret".Sha256())
    },
    AllowedScopes = {"api"},
    RequireClientSecret = false,
}
ASP.NET Core分布式项目实战(oauth密码模式identity server4实现)

新建控制台程序

dotnet new console --name PwdClient

添加 Nuget 包:IdentityModel

添加之后还原

dotnet restore

拷贝一份 ThirdPartyDemo 的 Program 过来修改

using System;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using Newtonsoft.Json.Linq;

namespace PwdClient
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // discover endpoints from metadata
            var client = new HttpClient();
            var disco = client.GetDiscoveryDocumentAsync("http://localhost:5000").Result;
            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }

            // // request token
            // var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            // {
            //     Address = disco.TokenEndpoint,

            //     ClientId = "client",
            //     ClientSecret = "secret",
            //     Scope = "api"
            // });

            // request token
            var tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address = disco.TokenEndpoint,

                ClientId = "pwdClient",
                ClientSecret = "secret",
                Scope = "api",

                UserName = "mingsonzheng",
                Password = "123456",
            });

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }

            Console.WriteLine(tokenResponse.Json);

            // call api
            var client2 = new HttpClient();
            client2.SetBearerToken(tokenResponse.AccessToken);

            var response = await client2.GetAsync("http://localhost:5001/weatherforecast");
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
            }
            else
            {
                var content = await response.Content.ReadAsStringAsync();
                Console.WriteLine(JArray.Parse(content));
            }
        }
    }
}

先启动 IdentityServerCenter,ClientCredentialApi

再启动 PwdClient,输出如下:

{
  "access_token": "eyJhbGciOiJSUzI1NiIsImtpZCI6ImZFd0d5VGQtY2FkaE9Oamp6ajc5THciLCJ0eXAiOiJhdCtqd3QifQ.eyJuYmYiOjE1ODY0NTA4ODQsImV4cCI6MTU4NjQ1NDQ4NCwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwIiwiYXVkIjoiYXBpIiwiY2xpZW50X2lkIjoicHdkQ2xpZW50Iiwic3ViIjoiMSIsImF1dGhfdGltZSI6MTU4NjQ1MDg4NCwiaWRwIjoibG9jYWwiLCJzY29wZSI6WyJhcGkiXSwiYW1yIjpbInB3ZCJdfQ.xAndZZqCfNGblZmyxLEmWYHFmy26g75kk7cOCkppmWWbmf3ISQVM66hTiGfgpC2xntorRDBPhDtVU0hmmmoEukycTIbeR1jdg8hYyKF2lcuFzTldOIs5ogtp84Gk0GcKkv0Ecurz5onAsZAMLjV_f2bMr8k2DPOA9062L5ULxqWuk00jK3S1f8FPACWGqO87MUIimt4YGxySggdzr2INwmqBOb8HZcA3gCoz9vxf0i_RNBvq_9D7YnfiGIAIevR_MAymDGoK-1KzENcmyS15yFnDClUjcVgFBAUUuNEiB4106w9Uft5Tao1EUxI0_oy7_HulDpSY0Cs4RCyL5mlU4Q",
  "expires_in": 3600,
  "token_type": "Bearer",
  "scope": "api"
}
[
  {
    "date": "2020-04-11T00:48:04.3089512+08:00",
    "temperatureC": 22,
    "temperatureF": 71,
    "summary": "Warm"
  },
  {
    "date": "2020-04-12T00:48:04.3089617+08:00",
    "temperatureC": 24,
    "temperatureF": 75,
    "summary": "Chilly"
  },
  {
    "date": "2020-04-13T00:48:04.308962+08:00",
    "temperatureC": 37,
    "temperatureF": 98,
    "summary": "Cool"
  },
  {
    "date": "2020-04-14T00:48:04.3089622+08:00",
    "temperatureC": -3,
    "temperatureF": 27,
    "summary": "Mild"
  },
  {
    "date": "2020-04-15T00:48:04.3089624+08:00",
    "temperatureC": 46,
    "temperatureF": 114,
    "summary": "Sweltering"
  }
]

课程链接

http://video.jessetalk.cn/course/explore

相关文章

ASP.NET&nbsp;Core分布式项目实战(第三方ClientCredential模式调用)–学习笔记

ASP.NET Core分布式项目实战(客户端集成IdentityServer)–学习笔记

ASP.NET Core分布式项目实战(业务介绍,架构设计,oAuth2,IdentityServer4)–学习笔记

ASP.NET Core分布式项目实战(课程介绍,MVP,瀑布与敏捷)–学习笔记

ASP.NET Core快速入门 — 学习笔记汇总
欢迎各位读者加入微信群一起学习交流,在公众号后台回复“加群”即可~~

ASP.NET Core分布式项目实战(oauth密码模式identity server4实现)

原文出处:微信公众号【DotNet NB】

原文链接:https://mp.weixin.qq.com/s/pvS8mbxj1U2xOEdrCMPezQ

本文观点不代表Dotnet9立场,转载请联系原作者。

发表评论

登录后才能评论

评论列表(1条)

  • Dotnet9
    Dotnet9 2020年5月15日 08:48

    这是个文章系列,代码和前面几节有关联,建议先查看前面几篇文章。
    另外,有条件观看原作者视频会有更多的收获。
    视频中使用的.net core版本较低,部分代码可能需要读者自行百度或谷歌,本系列文章都使用.net core 3.1编译通过。