返回顶部

Identity Server 4资源拥有者密码认证控制访问API(二)

基于上一篇文章中的代码进行继续延伸,只需要小小的改动即可,不明白的地方可以先看看本人上一篇文章及源码 Identity Server 4客户端认证控制访问API

  

 

一、QuickStartIdentityServer4项目中Config.cs增加如下配置

// 定义客户端认证方式
        public static IEnumerable<Client> Clients => new[]
        {
            // 客户端认证
            new Client
            {
                ClientId="sample_client", // 客户端id
                ClientSecrets =
                {
                    new Secret("sample_client_secret".Sha256()) // 客户端秘钥

                },
                AllowedGrantTypes=GrantTypes.ClientCredentials, // 授权类型为客户端
                AllowedScopes={ "sample_api" } // 设置该客户端允许访问的api范围
            },
            // 资源拥有者认证
            new Client
            {
                ClientId="sample_pass_client", // 客户端id
                ClientSecrets =
                {
                    new Secret("sample_client_secret".Sha256()) // 客户端秘钥

                },
                AllowedGrantTypes=GrantTypes.ResourceOwnerPassword, // 授权类型为资源拥有者
                AllowedScopes={ "sample_api" } // 设置该客户端允许访问的api范围
            }
        };

 

 二、Client项目中增加模拟请求资源拥有者认证,其他代码不变

// 资源拥有者认证
            var tokenResponse = await client.RequestPasswordTokenAsync(
                    new PasswordTokenRequest
                    {
                        Address = disco.TokenEndpoint,
                        ClientId = "sample_pass_client",
                        ClientSecret = "sample_client_secret",
                        UserName="admin",
                        Password="123"
                    }
                );

 

 三、项目测试

1、’postman模拟请求 http://localhost:5001/connect/token 获取token

 

 2、使用token请求api

 

 3、Client项目模拟客户端请求

 

学习链接:https://www.cnblogs.com/stulzq/p/7509648.html

 

posted @ 2022-07-11 23:29  SportSky  阅读(278)  评论(0编辑  收藏  举报
作者:SportSky 出处: http://www.cnblogs.com/sportsky/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。如果觉得还有帮助的话,可以点一下右下角的【推荐】,希望能够持续的为大家带来好的技术文章!想跟我一起进步么?那就【关注】我吧。