首页 > 其他 > 详细

IdentityServer4密码模式

时间:2021-09-02 21:40:23      阅读:24      评论:0      收藏:0      [点我收藏+]

书接上文。

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

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

现在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依然能够访问你的资源

IdentityServer4密码模式

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!