设为首页 加入收藏

TOP

asp.net core系列 55 IS4使用Identity密码保护API(一)
2019-09-17 19:06:57 】 浏览:54
Tags:asp.net core 系列 IS4 使用 Identity 密码保护 API

一.概述

  OAuth 2.0资源(web api)所有者密码授权,允许客户端(Client项目)向令牌服务(IdentityServer项目)发送用户名和密码,并获取代表该用户的访问令牌。在官方文档中讲到:规范通常建议不要使用“资源所有者密码授权”。当用户进行身份验证并请求访问令牌时,使用一个交互式OpenID Connect流程通常要好得多(下篇再了解)。

  本篇介绍“资源所有者密码授权”是因为这种授权允许我们快速启动IdentityServer。开源地址:Github 

  下面示例与官方示例有点区别,该示例使用了Identity密码保护API。关于asp.net core Identity的了解实现,查看之前章节或官方文档。示例中分别是IdentityServer令牌项目、 API资源项目、 Client访问项目。与上篇相比一样,还是三个项目,区别在于:

  (1) IdentityServer令牌项目换成了含有asp.net core Identity的MVC项目。

  (2) API资源项目没有变动。

  (3) Client访问项目使用了用户名和密码访问受保护的API。

 

二. IdentityServer项目

  IdentityServer令牌项目是包含了 Identity功能(安装:Install-Package IdentityServer4),在项目中,添加了Config.cs类和Startup.cs中加入了IdentityServer的启动配置。下面是MVC项目目录结构:

  (1) 添加用户

    IdentityServer类库中自带TestUser测试类,是DTO数据传输对象,存储用户及其声明(claims)。TestUser是用于测试中的内存(In-memory)用户对象。在正式环境下,获取数据库中的用户表(User),需要结合IdentityServer的IResourceOwnerPasswordValidator接口(不再本篇讲述中)。 下面通过在config.cs类中添加GetUsers方法获取用户密码,存储在TestUser数据传输对象中。

        /// <summary>
        ///获取用户,这些用户可以访问受密码保护的API
        /// </summary>
        /// <param name="provider"></param>
        /// <returns></returns>
        public static List<TestUser> GetUsers(ServiceProvider provider)
        {
            var webAppIdentityDemoUser = provider.GetRequiredService<UserManager<WebAppIdentityDemoUser>>();
            IList<WebAppIdentityDemoUser> users = null;
            //获取Identity的User表用户,条件是属于Administrator角色的用户
            users = webAppIdentityDemoUser.GetUsersInRoleAsync("Administrator").Result;

            List<TestUser> testUserList = new List<TestUser>();
            foreach (WebAppIdentityDemoUser user in users)
            {
                testUserList.Add(new TestUser() { SubjectId = user.Id.ToString(), Username = user.UserName, Password = user.PasswordHash });
            }
            return testUserList;
        }

  (2) 然后在Startup类的ConfigureServices方法中使用IdentityServer注入测试用户:

            ServiceProvider provider = services.BuildServiceProvider();

            var builder = services.AddIdentityServer()
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApis())
                .AddInMemoryClients(Config.GetClients())
                .AddTestUsers(Config.GetUsers(provider));

  (3) 定义客户端, 使用密码授予访问此API(资源范围:api1)

    在config.cs类中,定义客户端,通过修改AllowedGrantTypes枚举来简单地向现有客户端添加对授权类型的支持, 将以下代码添加到客户端配置中, 里面支持二个Client授权类型,分别是ClientCredentials使用凭证来访问令牌和ResourceOwnerPassword 使用密码来访问令牌。

      public static IEnumerable<Client> GetClients()
        {
            return new List<Client>
            {
                new Client
                {
                    ClientId = "client",

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

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

                    // scopes that client has access to
                    AllowedScopes = { "api1" }
                },
                // resource owner password grant client
                new Client
                {
                    ClientId = "ro.client",
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

                    ClientSecrets =
                    {
                        new Secret("secret".Sha256())
                    },
                    AllowedScopes = { "api1" }
                }
            };
        }

  

三.Client项目

  该Client项目类似于上篇介绍的Client项目,该项目名为ResourceOwnerClient, 该Client将收集用户名和密码,并在令牌请求期间,将其发送到IdentityServer令牌服务(WebAppIdentityDemo项目)

            // re
首页 上一页 1 2 下一页 尾页 1/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C#中Skip和Take的用法 下一篇C#常用修饰符

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目