1. 程式人生 > >.net core Identity集成IdentityServer(2) 實現IprofileService接口在accesstoken中增加自定義claims

.net core Identity集成IdentityServer(2) 實現IprofileService接口在accesstoken中增加自定義claims

實現 ets gen 配置 授權 spn cor devel color

導讀

1. 如何添加自定義的claims.


前請提要

目前我們擁有了三個web應用.

  1. localhost:40010, 驗證服務器
  2. localhost:40011, mvc客戶端, 充當webapp請求者
  3. localhost:40012, webapi, 資源, 受到驗證服務器的保護

在http://localhost:40011/Home/secure登錄之後, 我們看到了很多的claims, 其中有name, ( 來自aspnetUsers表的userName字段)

那麽, 如果我想在accesstoken中增加其他的字段呢, 比如, 用戶頭像url, 性別等等

那麽下面我們開始工作

打開驗證服務器(這次只需要修改驗證服務器)的Model/ApplicationUser文件, 添加兩個字段

技術分享圖片然後去對應的數據表增加兩個字段.

新增一個ProfileService繼承自IdentityServer4.Services.IProfileService

public class CustomProfileService : IProfileService
    {
        private readonly IUserClaimsPrincipalFactory<ApplicationUser> _claimsFactory;
        private readonly UserManager<ApplicationUser> _userManager;

        
public CustomProfileService(UserManager<ApplicationUser> userManager, IUserClaimsPrincipalFactory<ApplicationUser> claimsFactory) { _userManager = userManager; _claimsFactory = claimsFactory; } public async Task GetProfileDataAsync(ProfileDataRequestContext context) {
//獲得登錄用戶的ID var sub = context.Subject.GetSubjectId(); var user = await _userManager.FindByIdAsync(sub); //創建一個以當前用戶為主體的憑證 var principal = await _claimsFactory.CreateAsync(user); var claims = principal.Claims.ToList(); //idsv服務器的默認claim claims = claims.Where(claim => context.RequestedClaimTypes.Contains(claim.Type)).ToList(); //自定義claims區間 claims.Add(new Claim(JwtClaimTypes.GivenName, user.UserName)); claims.Add(new Claim("headimgurl", user.HeadImgUrl)); claims.Add(new Claim("gender", user.Gender)); //設置claims context.IssuedClaims = claims; } public async Task IsActiveAsync(IsActiveContext context) { var sub = context.Subject.GetSubjectId(); var user = await _userManager.FindByIdAsync(sub); context.IsActive = user != null; } }

然後在Startup的註冊idsv的地方添加自定義的ProfileService的註入即可

services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(AuthorizationConfig.GetIdentityResources())
.AddInMemoryApiResources(AuthorizationConfig.ApiResources())
.AddInMemoryClients(AuthorizationConfig.Clients())
.AddAspNetIdentity<ApplicationUser>()
.AddProfileService<CustomProfileService>();

運行起所有的服務

技術分享圖片技術分享圖片

左圖是mvc客戶端讀取的自定義claims, 右側是在mvc客戶端去請求受保護的webapi後, webapi拿到的信息


註意

通過ProfileService的使用, 可以不受管制地向客戶端發送claims.

這是什麽意思如何理解呢?

在我們的idsv的配置類中, 有IdentityResources, 有Clients, 有apiResources, 這些配置限制了客戶端能請求到的服務器資源.

在客戶端程序中的startup中, 我們能看到一句代碼

技術分享圖片

這就是客戶端添加能訪問的資源的地方. 我們將在以後的consent授權頁面去細說這方面的知識

那麽, 通過profileservice頒發的claims, 任意clients都能拿到

.net core Identity集成IdentityServer(2) 實現IprofileService接口在accesstoken中增加自定義claims