如何阅读JWT Token .NET 4.5的声明

时间:2017-09-22 14:34:15

标签: c# .net jwt bearer-token

我无法从Bearer JWT令牌中读取令牌声明。登录正在运行,http请求带有一个有效的jwt令牌到后端。 该应用程序在IIS7上自托管。 这是我在服务器端的代码:

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

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);

在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;
}

这是调试的标识变量: identity

2 个答案:

答案 0 :(得分:0)

我不知道你的AuthorizationServerProvider.cs出了什么问题, 但是从您在请求标题中提供jwt令牌的那一刻起,我认为它将以这种方式工作。

我在每个接受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);
    }
}

用法

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

注意我在使用Visual Studio 2017从线程中读取Current Principal时遇到了一些问题。 如果您仍然遇到问题,可以查看一下。 ClaimsPrincipal.Current Visual Studio 2017 different behavior

答案 1 :(得分:0)

我需要做的就是在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);
     }
}