Asp.net web api 从JWT令牌设置HttpContext.Current.User

Asp.net web api 从JWT令牌设置HttpContext.Current.User,asp.net-web-api,oauth-2.0,asp.net-web-api2,owin,jwt,Asp.net Web Api,Oauth 2.0,Asp.net Web Api2,Owin,Jwt,我正在使用Microsoft.Owin.Security.Jwt nuget包来保护我的webapi。当我将令牌作为头传递给webapi到请求中时,它将HttpContext.Current.User设置为预期值 由于封装了业务逻辑,我找不到设置HttpContext.Current.User的时刻 我不想一直使用identity.Claims搜索正确的声明,而是提取我需要的信息,并将自定义类设置为HttpContext.Current.User。是否可以使用Microsoft.Owin.Sec

我正在使用Microsoft.Owin.Security.Jwt nuget包来保护我的webapi。当我将令牌作为头传递给webapi到请求中时,它将HttpContext.Current.User设置为预期值

由于封装了业务逻辑,我找不到设置HttpContext.Current.User的时刻


我不想一直使用identity.Claims搜索正确的声明,而是提取我需要的信息,并将自定义类设置为HttpContext.Current.User。是否可以使用Microsoft.Owin.Security.Jwt?

不太清楚您的意思。HttpContext.Current.User会在您的令牌有效时自动设置(与密钥匹配且未过期)。 您可以编写一些扩展方法来检索其他值。例如:

public static class IdentityHelpers
{
    public static string GetUserId(this IIdentity identity) 
    {
        ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;

        if (claimsIdentity.Claims.FirstOrDefault(x => x.Type == "UserId") != null) {
            return claimsIdentity.Claims.FirstOrDefault(x => x.Type == "UserId").Value;
        }

        return "0";
    }

    public static string GetUserName(this IIdentity identity) 
    {
        return identity.Name;
    }
}
HttpContext.Current.user.GetUserName(); 
然后,您可以拨打电话,例如:

public static class IdentityHelpers
{
    public static string GetUserId(this IIdentity identity) 
    {
        ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;

        if (claimsIdentity.Claims.FirstOrDefault(x => x.Type == "UserId") != null) {
            return claimsIdentity.Claims.FirstOrDefault(x => x.Type == "UserId").Value;
        }

        return "0";
    }

    public static string GetUserName(this IIdentity identity) 
    {
        return identity.Name;
    }
}
HttpContext.Current.user.GetUserName(); 


无论你把那门课包括在哪里。

现在我用这种方式解决。我想截获Owin设置此HttpContext.Current.User并使用从声明中提取的值设置自定义类的瞬间。抱歉,无法帮助您。我发现整个Owin的概念相当模糊,而且我还有很多辅助方法可以检索我的声明,就像我在回答中所展示的那样。我将继续回答这个问题,希望有一个好的答案