簡體   English   中英

.Net Core IdentityServer4獲取經過身份驗證的用戶

[英].Net Core IdentityServer4 Get Authenticated User

我正在試圖弄清楚如何使用.Net-Core 2從身份服務器4中檢索登錄用戶。我的身份驗證目前正在運行,我只想弄清楚如何從HTTP上下文中檢索聲明身份。

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
}).AddIdentityServerAuthentication(o =>
{
    o.Authority = IDP_AUTHORITY_URL;
    o.RequireHttpsMetadata = false;
    o.ApiName = API_ID;
    o.JwtBearerEvents = new JwtBearerEvents
    {
        OnTokenValidated = async tokenValidationContext =>
        {
            var claimsIdentity = tokenValidationContext.Principal.Identity as ClaimsIdentity;
            if (claimsIdentity == null)
            {
                return;
            }

            string userId = claimsIdentity.Claims.FirstOrDefault(c => c.Type == "sub").Value;

            if (string.IsNullOrEmpty(userId))
            {
                throw new AuthenticationException("Error obtaining Subject claim");
            }
        }
    };
});

我有一項服務,我需要登錄用戶,我無法弄清楚如何獲得它。

public interface IAuthenticatedUserManager<T>
    where T: class
{
    T GetLoggedInUser();
}

public class AuthenticatedUserManager : IAuthenticatedUserManager<User>
{
    public User GetLoggedInUser()
    { 
        //HttpContext.Current
    }
}

它用於HttpContext.Current,但我不認為它是.Net-Core 2中的一個選項。如何從.Net Core 2中檢索我的ClaimsIdentity?

這應該適合你:

var user = (HttpContext.User.Identity as ClaimsIdentity);

然后用戶對象具有您所需的功能。

我想出了如何做到這一點。 因為,我正在使用需要HttpContext注入的自定義服務,我需要注冊一個訪問器作為注入:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

然后在我的身份驗證管理器中,我可以訪問我的HttpContext

public class UserAuthenticationManager : IUserAuthenticationManager
{
    HttpContext _httpContext;

    public UserAuthenticationManager(IHttpContextAccessor httpContextAccessor)
    {
        this._httpContext = httpContextAccessor?.HttpContext;
    }
    public ClaimsIdentity GetClaimsIdentity()
    {
        return (this._httpContext.User.Identity as ClaimsIdentity);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM