ASP.NET Core distributed project combat (oauth password mode identity server4 realization) - Study Notes

Task 12: oauth password mode to achieve identity server4

After the password mode is more stringent than the client mode, we need a third party to enter a user name and password to access the API

Introduced into the test namespace IdentityServerCenter in the Config

using IdentityServer4.Test;

And add a way to get TestUser

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

Formal environment, then read from the database

Copy the client list to add a client, modify ClientId and AllowedGrantTypes

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

In AddTestUsers Startup

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

Start IdentityServerCenter and ClientCredentialApi

Get access_token

In the config you can modify the configuration RequireClientSecret, so that the interface does not call parameter passing client_secret

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

New console program

dotnet new console --name PwdClient

Add Nuget package: IdentityModel

After adding the reduction

dotnet restore

ThirdPartyDemo over a copy of the Program modification

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));
            }
        }
    }
}

First start IdentityServerCenter, ClientCredentialApi

Restart PwdClient, output:

{
  "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"
  }
]

Course Link

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

Creative Commons License

This work is Creative Commons Attribution - NonCommercial - ShareAlike 4.0 International License Agreement for licensing.

Welcome to reprint, use, repost, but be sure to keep the article signed by Zheng Ziming (containing links: http://www.cnblogs.com/MingsonZheng/ ), shall not be used for commercial purposes, be sure to publish the same work based on the paper license modification .

If you have any questions, please contact me ([email protected]).

Guess you like

Origin www.cnblogs.com/MingsonZheng/p/12670821.html