IdentityServer4密码模式

书接上文。

做完了客户端模式来做密码模式。

密码模式需要用户和密码。

现在Config里面添加个方法

 public static List<TestUser> GetUsers()
        {
            return new List<TestUser>()
        {
            new TestUser()
            {
                //用户名
                 Username="apiUser",
                 //密码
                 Password="apiUserPassword",
                 //用户Id
                 SubjectId="0",
                 //在IdentityServer4中,TestUser有一个Claims属性,允许自已添加Claim,有一个ClaimTypes枚举列出了可以直接添加的Claim 同时需要在ApiResouce的构造函数有一个重载支持传进一个Claim集合,用于允许该Api资源可以携带那些Claim
                 Claims=new List<Claim>(){
                     new Claim(ClaimTypes.Role,"admin")
                 }
            }
        };
        }

  Clients方法里面增加一个客户端变成这样

public static IEnumerable<Client> Clients =>
            new Client[]
            { 
                //1:客户端模式
            new Client
            {
                ClientId = "apiClientCd",
                ClientName = "Client Credentials Client",

                AllowedGrantTypes = GrantTypes.ClientCredentials,
                ClientSecrets = { new Secret("apiSecret".Sha256()) },

                AllowedScopes = { "secretapi" }
            },
            //密码模式
             new Client()
                {
                    //客户端Id
                     ClientId="apiClientPassword",
                     //客户端密码
                     ClientSecrets={new Secret("apiSecret".Sha256()) },
                     //客户端授权类型,ClientCredentials:客户端凭证方式
                     AllowedGrantTypes=GrantTypes.ResourceOwnerPassword,
                     //允许访问的资源
                     AllowedScopes={
                        "secretapi"
                    }
                }
            };

在StartUp.cs里面增加一个 builder.AddTestUsers(Config.GetUsers()),表示验证用户。

API项目不变

然后用postman请求,此时注意,需要加两个参数,用户名和密码,就是你增加的用户名和密码

 复制这个token依然能够访问你的资源。

原文地址:https://www.cnblogs.com/fanlin92/p/15219974.html