且构网

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

经过IdentityServer身份验证后,如何在WebAPI控制器上获取用户信息?

更新时间:2023-09-07 16:48:22

如果使用owin,则可以尝试以下代码.

if you use owin, you can try this code.

 var owinUser = TryGetOwinUser();
 var claim= TryGetClaim(owinUser, "email");
 string email = claim.Value;

 private ClaimsPrincipal TryGetOwinUser()
    {
        if (HttpContext.Current == null)
            return null;

        var context = HttpContext.Current.GetOwinContext();
        if (context == null)
            return null;

        if (context.Authentication == null || context.Authentication.User == null)
            return null;

        return context.Authentication.User;
    }

    private Claim TryGetClaim(ClaimsPrincipal owinUser, string key)
    {
        if (owinUser == null)
            return null;

        if (owinUser.Claims == null)
            return null;

        return owinUser.Claims.FirstOrDefault(o => o.Type.Equals(key));
    }