简体   繁体   English

如何从JWT令牌.NET 4.5中读取声明

[英]How to read Claims from JWT Token .NET 4.5

I can't read token claims from Bearer JWT token. 我无法读取Bearer JWT令牌的令牌声明。 Login is working, the http request comes with a valid jwt token to the backend. 登录正常,http请求带有到后端的有效jwt令牌。 The application is self hosted on IIS7. 该应用程序是自托管在IIS7上的。 Here is my code on server side: 这是我在服务器端的代码:

SecurityConfig.cs SecurityConfig.cs

app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
    Provider = new AuthorizationServerProvider() ,
    AccessTokenFormat = new JwtFormat(TimeSpan.FromHours(24))
});

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

AuthorizationServerProvider.cs AuthorizationServerProvider.cs

ClaimsIdentity id = new ClaimsIdentity(context.Options.AuthenticationType);

id.AddClaim(new Claim(InosysClaimTypes.UserId, Convert.ToString(appContext.UserId)));

id.AddClaim(new Claim(InosysClaimTypes.Username, context.UserName));
id.AddClaim(new Claim(InosysClaimTypes.Password, context.Password));

id.AddClaim(new Claim(InosysClaimTypes.FirNr, Convert.ToString(appContext.FirmenNummer)));
id.AddClaim(new Claim(InosysClaimTypes.FirNdl, Convert.ToString(appContext.Niederlassung)));
id.AddClaim(new Claim(InosysClaimTypes.Bereich, Convert.ToString(appContext.Bereich)));

id.AddClaim(new Claim(InosysClaimTypes.Sprache, Convert.ToString(appContext.Sprache)));
id.AddClaim(new Claim(InosysClaimTypes.SchiffNummern, appContext.SchiffNummern == null ? "" : string.Join(",", appContext.SchiffNummern)));
id.AddClaim(new Claim(InosysClaimTypes.Geschaeftsjahr, Convert.ToString(appContext.Geschaeftsjahr)));

var principal = new ClaimsPrincipal(id);
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
    HttpContext.Current.User = principal;
}

context.Validated(id);

In the ApiController i try to get the caller's payload information like this: 在ApiController中,我尝试获取调用者的有效负载信息,如下所示:

ClaimsIdentity identity = User.Identity as ClaimsIdentity;

if (identity != null)
{
    appContext.UserId = Convert.ToInt32(identity.FindFirst(InosysClaimTypes.UserId).Value);
    appContext.Username = identity.FindFirst(InosysClaimTypes.Username).Value;
}

That is the identity variable debugged: identity 也就是说调试,身份变量: 身份

I don't know what is going wrong with your AuthorizationServerProvider.cs , But from the moment you provide a jwt token in your request header i think it will work this way. 我不知道您的AuthorizationServerProvider.cs出了什么问题,但是从您在请求标头中提供jwt令牌的那一刻起,我认为它将以这种方式工作。

I process the Header with an AuthorizeAttribute on each Controller accepting JWT authorization to set the Current Principal for the request. 我在每个接受JWT授权以设置请求的当前主体的Controller上使用AuthorizeAttribute处理Header。

public class JwtAuthentication : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var authHeader=actionContext.Request.Headers.Authorization;
        if (authHeader!=null&& !String.IsNullOrWhiteSpace(authHeader.Parameter))
            System.Threading.Thread.CurrentPrincipal = JwtAuthenticationHandler.GetPrincipal(authHeader.Parameter);
        return ClientAuthorize.Authorize(Roles);
    }
}

Usage 用法

[JwtAuthentication(Roles = "User")]
public class ChatBotController : ApiController
{}

Note i have been experiencing some issues with visual studio 2017 reading the Current Principal from the Thread. 请注意,我在Visual Studio 2017中遇到一些问题,该问题从线程读取Current Principal。 You might have a look at if you still experience issues. 如果您仍然遇到问题,可以看看。 ClaimsPrincipal.Current Visual Studio 2017 different behavior ClaimsPrincipal.Visual Studio 2017当前行为不同

All I needed to do was to implement the unprotect function in the JWTFormat class 我要做的就是在JWTFormat类中实现unprotect函数

public AuthenticationTicket Unprotect(string protectedText)
{           
      try
      {
          var handler = new JwtSecurityTokenHandler();

          AppContext = new AppContext(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)
                    {
                        EventLogPriority = Properties.Settings.Default.EventLogPriority
                    };

          SecurityToken validToken;

          _validationParameters.IssuerSigningKey = new SymmetricSecurityKey(TextEncodings.Base64Url.Decode(Secret));
                    ClaimsPrincipal principal = handler.ValidateToken(protectedText, _validationParameters, out validToken);

           var validJwt = validToken as JwtSecurityToken;

           if (validJwt == null)
           {
               throw new ArgumentException("Invalid JWT");
           }

           ClaimsIdentity identity = principal.Identities.FirstOrDefault();
           return new AuthenticationTicket(identity, new AuthenticationProperties());
     }            
     catch (SecurityTokenException ex)
     {
          var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Access Token is manipulated" };
                    throw new HttpResponseException(msg);
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 直接从令牌中获取 JWT 声明,ASP Net Core 2.1 - Get JWT claims directly from the token, ASP Net Core 2.1 如何在 OpenIdConnect in.Net Core 中向 Jwt 令牌添加自定义声明 - How to add custom claims to Jwt Token in OpenIdConnect in .Net Core 从 WebAPI Controller - JWT 令牌获取声明, - Get claims from a WebAPI Controller - JWT Token, 从 JWT 令牌中获取声明、权限和角色 - Get Claims, Permissions and Roles from JWT Token 从 jwt 令牌获取声明到 context.User.Claims - Get claims from jwt token into context.User.Claims 无法使用 ASP.NET Core 从 JWT 令牌中获取声明 - Can't get claims from JWT token with ASP.NET Core 无法将声明Cookie从.NET 4.5解密到.NET 3.5 - Unable to decrypt claims cookie from .NET 4.5 to .NET 3.5 如何从 .NET Core 6.0 中的 JWT 安全令牌读取自定义声明值 - How to read custom claim value from JWT security token in .NET Core 6.0 如何在Asp.NET Core WEB API中使用.Net(C#)在有效载荷中使用自定义JSON声明创建JWT令牌 - How to create a JWT token with custom JSON claims in Payload using .Net (C#) in Asp.NET Core WEB API 从 Google 身份验证接收 JWT 令牌而不是接收声明 - Receive JWT token from Google auth instead of receiving claims
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM