且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用IdentityServer 4时如何在Api Project中添加其他声明

更新时间:2023-02-20 18:59:32

在您的API项目中,您可以将自己的事件处理程序添加到options.JwtBearerEvents.OnTokenValidated.这是设置ClaimsPrincipal的地方,您可以向身份添加声明或向委托人添加新身份.

In your API project you can add your own event handler to options.JwtBearerEvents.OnTokenValidated. This is the point where the ClaimsPrincipal has been set and you can add claims to the identity or add a new identity to the principal.

services.AddAuthentication("Bearer")
   .AddIdentityServerAuthentication(options =>
   {
       options.Authority = "http://localhost:5100";
       options.RequireHttpsMetadata = false;
       options.ApiName = "beehouse.scope.ensino-api";

       options.JwtBearerEvents.OnTokenValidated = async (context) => 
       {
           var identity = context.Principal.Identity as ClaimsIdentity;

           // load user specific data from database
           ...

           // add claims to the identity
           identity.AddClaim(new Claim("Type", "Value"));
       };
   });

请注意,此操作将在对API的每个请求上运行,因此,如果您要从数据库加载信息,则***缓存声明.

Note that this will run on every request to the API so it's best to cache the claims if you're loading info from database.

此外,Identity Server仅应负责标识用户,而不是标识用户的身份.它们的作用是特定于应用程序的(角色,权限等),因此您正确地认识到这一点并避免了与Identity Server的逻辑交叉.

Also, Identity Server should only be responsible for identifying users, not what they do. What they do is application specific (roles, permissions etc.) so you're correct in recognising this and avoiding the logic crossover with Identity Server.