服务器添加角色
Hey guys, if you’ve worked on Identity Server 4 surely you’ll notice there is a lack of tutorial on how to-do somethings. For example how to implement roles, and using azure active directory (AAD), splitting data to server and etc. For this tutorial we will tackle on how to implement roles on IdentityServer4 running on ASP.NET Identity setup.
大家好,如果您使用过Identity Server 4,肯定会发现缺少有关如何做某事的教程。 例如,如何实现角色以及如何使用Azure活动目录(AAD),将数据拆分到服务器等。在本教程中,我们将讨论如何在ASP.NET Identity安装程序上运行的IdentityServer4上实现角色。
Come on, let’s jump in!
来吧,让我们跳进去!
先决条件 (Prerequisites)
First of all, you must have a .NET Core 3.1 SDK (Software Development Kit) installed in your computer and I also assumed you are currently running Windows 10 or some Linux with proper environment set.
首先,您必须在计算机中安装.NET Core 3.1 SDK (软件开发工具包) ,并且我还假定您当前正在运行Windows 10或具有适当环境设置的某些Linux。
And the IdentityServer4 package on which we will dive in. The IdentityServer as a whole has been one of the de-facto standard in large scale deploy-able authentication service for .NET driven ecosystem. It uses OpenID Connect and OAuth 2.0 as base technology.
和IdentityServer4 整体上,IdentityServer一直是针对.NET驱动的生态系统的大规模可部署身份验证服务中的事实上的标准之一。 它使用OpenID Connect和OAuth 2.0作为基本技术。
那么我们从哪里开始呢? (So where do we start?)
The first thing we need to do, is to fetch the official starter template for IdentityServer4. In order to do that we need execute the following code below:
我们需要做的第一件事是获取IdentityServer4的官方入门模板。 为此,我们需要执行以下代码:
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/97a643cafeafe3baafd1796b37b79fbe.png)
The command above will install the IdentityServer4 template in your workstation.
上面的命令将在您的工作站中安装IdentityServer4模板。
After installing the official templates, we create and bootstrap our project on which we will call Is4RoleDemo.
安装官方模板后,我们创建并引导我们的项目,该项目将称为Is4RoleDemo。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/7896ff2e8398b9e5318bbc1063bb7be6.png)
As a rule of thumb, always run the bootstrapped code first to see if there are no errors and whatsoever. Then if there are no problems commit it to a version control system (VCS), so you could rollback if there’s a problem.
根据经验,请始终先运行引导代码,以查看是否没有错误以及任何错误。 然后,如果没有问题,请将其提交到版本控制系统(VCS),以便在出现问题时进行回滚。
We can now start modifying the project. Start by editing the Config.cs which can be found on the root directory.
现在,我们可以开始修改项目。 首先编辑可以在根目录下找到的Config.cs 。
The Config.cs contains initial data that can be used to run IdentityServer4 for in-memory storage setup. The in-memory storage should only be used in non-production environment.
Config.cs包含可用于运行IdentityServer4进行内存中存储设置的初始数据。 内存中的存储只能在非生产环境中使用。
First, we insert and create a new client on the variable named clients inside Config.cs file. This new config will require the client to have PKCE (Proof Key for Code Exchange) enabled authentication and verification (currently authentication with PKCE is now the standard in OAuth 2.0).
首先,我们在Config.cs文件中名为client的变量上插入并创建一个新客户端。 此新配置将要求客户端具有PKCE(代码交换证明密钥)启用的身份验证和验证(目前,使用PKCE进行身份验证现在是OAuth 2.0中的标准)。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/fea38560f9626aba367f9f108508426a.png)
After configuring the clients, we need to add roles to the initial seed data. Edit the SeedData.cs file and add the following before the user seed data.
配置客户端后,我们需要向初始种子数据添加角色。 编辑SeedData.cs文件,并在用户种子数据之前添加以下内容。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/1cd73bbec4611490057eac262bef820b.png)
The code above specifies two new roles which are member and admin. After adding the roles, we need to assign the roles to the seed users. Add the code below after the user initialization specifically alice’s user initialization.
上面的代码指定了两个新角色,分别是member和admin 。 添加角色后,我们需要将角色分配给种子用户。 用户初始化之后,特别是alice的用户初始化之后,添加以下代码。
![Image for post](https://miro.medium.com/max/9999/1*Yh7gGZ5QbH9nYSCwRGO96g.png)
What this does is, it will add the specific role to the user on the AspNetRoles mapping table. Same with alice put the code below bob’s user initialization in SeedData.cs.
这是什么,它将在AspNetRoles映射表上向用户添加特定角色。 与爱丽丝相同,将代码放在bob的用户初始化下方的SeedData.cs中。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/34342727d5afb4ed3f33523fa53a2691.png)
With all that implemented, adding roles and assigning roles to users. We need now to get the roles and put it on to user claims and return it as part of user info.
完成所有这些操作后,即可添加角色并为用户分配角色。 现在,我们需要获取角色并将其放入用户声明中,并将其作为用户信息的一部分返回。
To return the roles on claims we will implement a profile service that will inject the roles. To do that, we create a folder Services and a class file named ProfileService.cs inside it.
为了返回声明中的角色,我们将实现一个配置文件服务,该服务将注入角色。 为此,我们在其中创建一个文件夹Services和一个名为ProfileService.cs的类文件。
The ProfileService class will inherit the IProfileService trait. Then we override the method GetProfileDataAsync(ProfileDataRequestContext context) inside the class and put the code below.
ProfileService类将继承IProfileService特性。 然后,在类内重写方法GetProfileDataAsync(ProfileDataRequestContext context)并将代码放在下面。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/d77dfe1a928a27f4a5952a56b5f55120.png)
The code above specifically search for the specific user and check whether that returned user data is assigned to any roles. And if it satisfy that condition then modify the current claims adding the role assigned for that user.
上面的代码专门搜索特定用户,并检查是否将返回的用户数据分配给任何角色。 如果满足该条件,则修改当前声明,添加为该用户分配的角色。
Check the whole source for the ProfileService class below and compare it with your current code.
检查下面的ProfileService类的整个源,并将其与当前代码进行比较。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/1323fc32cfcbb8a235feedf78d210a4a.png)
We should head now to the Startup.cs file to create and initialize the class ProfileService class that we’ve created. Put the code inside the ConfigureServices(IServiceCollection services) method. This will scoped the class and inject our custom implementation to the service.
现在,我们应该进入Startup.cs文件,以创建和初始化我们创建的ProfileService类。 将代码放入ConfigureServices(IServiceCollection services)方法中。 这将确定类的作用域并将我们的自定义实现注入服务。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/10dab8fca374539cda0e5fcc566d26f6.png)
Finally, build and run the project to see if there are any errors using dotnet build and dotnet run. If everything is okay, test the implementation using Postman.
最后,使用dotnet build和dotnet run生成并运行项目,以查看是否存在任何错误。 如果一切正常,请使用Postman测试实现。
On postman window, make sure to set the authentication to OAuth 2.0 with PKCE and query to /userinfo endpoint of the identity service. If everything is correct, on the OAuth 2.0 get token tab — copy the JWT token returned by our identity service.
在邮递员窗口上,确保使用PKCE将身份验证设置为OAuth 2.0,并查询到身份服务的/ userinfo端点。 如果一切正确,请在OAuth 2.0的“获取令牌”标签上-复制我们的身份服务返回的JWT令牌。
After copying the JWT token, we put the token on a JWT analyzer site like https://www.jsonwebtoken.io/. The site will analyze and return a JSON structure on which we will use to confirm if the role has been added properly.
复制JWT令牌后,我们将令牌放在JWT分析器站点上,例如https://www.jsonwebtoken.io/ 。 该站点将分析并返回一个JSON结构,我们将在该JSON结构上确认角色是否已正确添加。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/b3ccd00c7e6eca39e8a8e360a1120c8e.png)
If you look above the JSON, you’ll see there is a role field included that means we succeeded in adding roles to the claims. Otherwise, debug and see the ProfileService class if the user is returning roles.
如果您在JSON上方查看,则会看到其中包含一个角色字段,这意味着我们已成功将角色添加到声明中。 否则,请调试并查看ProfileService类(如果用户正在返回角色)。
(可选)连接到MVC ASP.NET Core项目 ((Optional) Connecting to MVC ASP.NET Core projects)
To use the identity service we created in your own MVC project. First and foremost, we need to add in the MVC project the Microsoft.AspNetCore.Authentication.OpenIdConnect package using NuGet package manager.
要使用我们在您自己的MVC项目中创建的身份服务。 首先,我们需要使用NuGet包管理器在MVC项目中添加Microsoft.AspNetCore.Authentication.OpenIdConnect包。
Then on Startup.cs we add and configure the OpenId Connect driver to connect to our newly created identity service. Then modify the AddOpenIdConnect option and add the code below, this will map the roles to the authorize attribute field roles.
然后在Startup.cs上,添加并配置OpenId Connect驱动程序以连接到我们新创建的身份服务。 然后修改AddOpenIdConnect选项并添加以下代码,这会将角色映射到authorize属性字段角色。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/d02046fa76618615aabe7610880f3328.png)
AddOpenIdConnect methodAddOpenIdConnect method
To use the roles in controllers you need to import Microsoft.AspNetCore.Authorization namespace. This will let you use the authorize attribute to secure the class or method that you intend to filter out users.
要在控制器中使用角色,您需要导入Microsoft.AspNetCore.Authorization命名空间。 这将使您可以使用authorize属性来保护要过滤出用户的类或方法。
![Image for post](https://i-blog.csdnimg.cn/blog_migrate/e4805d5345e5ebfc37f93802fe98b4b5.png)
I think that’s all for it, check the full source repository in following link below.
我认为仅此而已,请在下面的链接中查看完整的源存储库。
结论 (Conclusion)
Working with IdentityServer4 is somewhat pain in the ass — as developer support is locked behind a paywall. There are many ways to put roles in claims, but I think this is the most simplified and easiest implementation there is. With roles you can now filter out users accessing specific endpoints.
与IdentityServer4一起工作有点麻烦-因为开发人员支持被锁定在付费专线后面。 在索赔中放置角色的方法有很多,但是我认为这是最简化和最简单的实现。 使用角色,您现在可以筛选出访问特定端点的用户。
You can found the complete repository here.
您可以在此处找到完整的存储库。
Follow me for similar article, tips, and tricks ❤.
跟我来获取类似的文章,技巧和窍门❤。
翻译自: https://medium.com/@ffimnsr/adding-identity-roles-to-identity-server-4-in-net-core-3-1-d42b64ff6675
服务器添加角色