identityserver4 踩坑之不同API的ClaimsPrincipal獲取用戶信息的Type不一致


在微服務項目中使用的Identityserver4,給各個API添加認證時看到下面兩種方式,寫法一是原始的寫法,寫法二是Identityserver4封裝的寫法,主要是在根據token獲取用戶信息時存在差異。

寫法一獲取用戶ID時的claim的type是 http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier  ,對應System.Security.Claims下的 ClaimTypes.NameIdentifier

寫法二獲取用戶ID時的claim的type是 sub,對應IdentityModel下的 JwtClaimTypes.Subject

如果你獲取用戶信息的方法在項目中不是公用的,那你可以分開寫,每個API寫自己的獲取信息;如果你獲取用戶信息的方法在項目中是公用的那就要統一認證寫法了,不然就有問題,我就是這個有問題的。

因為使用的認證方法不一樣,對應的解析結果也不一樣,然后有些API就報錯了。

 

string IdentityUrl= Configuration["IdentityUrl"];
       // 寫法1
            //services.AddAuthentication("Bearer")
            //     .AddJwtBearer("Bearer", options =>
            //     {
            //         options.Authority = IdentityUrl;
            //         options.RequireHttpsMetadata = false;
            //         options.Audience = "orderapi";
            //     });
            //微服務中保持結構一致,要么多個API服務都使用上面的結構,要么統一用下面的結構,不一致會對 ClaimsPrincipal 解析不一致

       // 寫法2 services.AddAuthentication(options => { options.DefaultScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; options.DefaultSignInScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; options.DefaultForbidScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme; }) .AddIdentityServerAuthentication(options => { options.Authority = IdentityUrl; options.ApiName = "orderapi"; options.RequireHttpsMetadata = false; });

 

這是我獲取用戶ID的方法

 

public static int GetUserId(ClaimsPrincipal User)
        {
            
            var claim = User.Claims.Where(a => a.Type == JwtClaimTypes.Subject).FirstOrDefault();
            return Convert.ToInt32(claim.Value);
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM