当前位置:网站首页>[one by one series] identityserver4 (III) user name and password

[one by one series] identityserver4 (III) user name and password

2022-06-23 18:59:00 DDGarfield

Continue IdentityServer4, We introduced IdentityServer4 Realization OAuth2.0 One of the authorization methods is client certificate , Let's move on to OAuth2.0 Another way of authorization is password ,Resource Owner Password Credentials.

  • post request token?grant_type=password&username=USERNAME&password=PASSWORD&client_id=CLIENT_ID&client_secret=secret

From above url Of querystring Parameters can be seen , Here is the need to provide the user's user name and password , This is quite common in traditional projects

  • web Background management system
  • C/S client

1. to update IdentityServer

Because of the first part 【One by One series 】IdentityServer4( Two ) Use client credentials (Client Credentials) Protect API Resources have been created IdentityServer project , We just need IdentityServer4 Register users and add new clients in .

1.1 Registered users

There is no user involved in the client credentials , But the cipher is different , User name and password are required , Naturally, user data is needed . Of course, this content belongs to OpenID Connect 了 , Because it's about authentication .

We are Config.cs Add user data inside

public static List<TestUser> TestUsers =>
            new List<TestUser>
            {
                new TestUser()
                {
                    SubjectId="1",
                    Username="admin",
                    Password="admin123456!",
                    Claims=
                    { 
                        new Claim(JwtClaimTypes.Name,"RandyField"),
                        new Claim(JwtClaimTypes.GivenName,"Randy"),
                        new Claim(JwtClaimTypes.FamilyName,"Field"),
                        new Claim(JwtClaimTypes.Email,"[email protected]"),
                        new Claim(JwtClaimTypes.EmailVerified,"true",ClaimValueTypes.Boolean),
                        new Claim(JwtClaimTypes.WebSite,"http://www.randyfield.cn"),
                        new Claim(JwtClaimTypes.FamilyName,"Randy"),
                        new Claim(JwtClaimTypes.Address,[email protected]" Chengdu high tech Zone, Sichuan Province ")
                    }              
                }
            };

1.2 Register identity resources

The code is as follows :

public static IEnumerable<IdentityResource> IdentityResources =>
            new IdentityResource[]
            {
       // You have to add , Otherwise, it will be invalid scope error 
                new IdentityResources.OpenId(),
                new IdentityResources.Profile()
            };

1.3 Register a new client

The code is as follows :

        public static IEnumerable<Client> Clients =>
            new Client[]
            {
                 new Client
                    {
                        ClientId = "client app",

                        // no interactive user, use the clientid/secret for authentication
                        AllowedGrantTypes = GrantTypes.ClientCredentials,

                        // secret for authentication
                        ClientSecrets =
                        {
                            new Secret("secret-123456".Sha256())
                        },

                        // scopes that client has access to
                        AllowedScopes = { "api1" }
                    },
            
             //Resource Owner Password Credentials Client
                 new Client
                     {
                        ClientId="client pwd",
                        AllowedGrantTypes=GrantTypes.ResourceOwnerPassword,
                        ClientSecrets=
                         {
                            new Secret("secret-654321".Sha256())
                         },
                        AllowedScopes={ "api1",
                         IdentityServerConstants.StandardScopes.OpenId,
                         IdentityServerConstants.StandardScopes.Profile }
                     },
            };

Here is the client AllowedScopes except api resources , Additional users are specified Identity resources

2. Create client

Here we still use the client console program in the previous article , Just add code , Analog password Authorization

2.1 code - request Idisconvery endpoint

A little , It's the same as the first one

2.2 code - request access token

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

                ClientId = "client pwd",
                //ClientId = "client",
                ClientSecret = "secret-654321",
                Scope = "api1 openid profile",

                UserName= "admin",
                Password= "admin123456!"
            });

            if (tokenResponse1.IsError)
            {
                Console.WriteLine(tokenResponse1.Error);
                return;
            }
  • RequestClientCredentialsTokenAsync Replace with RequestPasswordTokenAsync
    • Request parameters ClientCredentialsTokenRequest Replace with PasswordTokenRequest
  • The user name and password , Is in the IdentityServer Registered users
  • ClientId And ClientSecret I won't go into that
  • Scope Point out api Resources and Identity resources

3. test

  • start-up IdentityServer
cd .\IdentityServer\
dotnet run
  • start-up webapi
cd .\webapi\
dotnet run
  • use vs start-up client

3.1 obtain access-token

We go through http://jwt.calebb.net/ analysis

3.2 call api

3.3 Get identity information

call userinfo Endpoint , Get identity information

原网站

版权声明
本文为[DDGarfield]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231758268297.html