从ASP.NET Core 2.0 API中获取JWT令牌的声明

时间:2018-01-07 04:48:56

标签: asp.net asp.net-web-api asp.net-core jwt asp.net-core-2.0

我在ASP.NET Core 2.0 Web和API应用程序中使用混合身份验证。这意味着两个cookie,现在添加JWT token

应用程序的Web部分使用cookie,在API部分中,我想使用JWT令牌。

我的问题是如何从JWT token获得声明?在我的网络控制器中,我可以简单地使用HttpContext.User;来获取存储在cookie中的声明。如何在我想要使用JWT token的API方法中处理它?<​​/ p>

这是我的AuthenticationBuilder:

public static void MyAuthenticationConfig(IServiceCollection services, IConfiguration configuration)
{
   services.AddAuthentication(options =>
   {
      options.DefaultAuthenticateScheme = "myApp_cookie";
      options.DefaultChallengeScheme = "myApp_cookie";
    })
    .AddCookie("myApp_cookie", options =>
    {
      options.AccessDeniedPath = "/Unauthorized";
      options.LoginPath = "/Login";
    })
    .AddCookie("social_auth_cookie")
    .AddOAuth("LinkedIn", options =>
    {
      options.SignInScheme = "social_auth_cookie";

      options.ClientId = "my_client_id";
      options.ClientSecret = "my_secret";

      options.CallbackPath = "/linkedin-callback";

      options.AuthorizationEndpoint = "https://www.linkedin.com/oauth/v2/authorization";
      options.TokenEndpoint = "https://www.linkedin.com/oauth/v2/accessToken";
      options.UserInformationEndpoint = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,picture-url,picture-urls::(original))";

      options.Scope.Add("r_basicprofile");
      options.Scope.Add("r_emailaddress");

      options.Events = new OAuthEvents
      {
         OnCreatingTicket = OnCreatingTicketLinkedInCallBack,
         OnTicketReceived = OnTicketReceivedCallback
       };
    })
    .AddFacebook(options =>
    {
        options.SignInScheme = "social_auth_cookie";
        options.AppId = "my_app_is";
        options.AppSecret = "my_secret";
        options.Events = new OAuthEvents
        {
           OnCreatingTicket = OnCreatingTicketFacebookCallback,
           OnTicketReceived = OnTicketReceivedCallback
         };
     })
     .AddGoogle(options =>
     {
         options.SignInScheme = "social_auth_cookie";
         options.ClientId = "my_id.apps.googleusercontent.com";
         options.ClientSecret = "my_secret";
         options.CallbackPath = "/google-callback";
         options.Events = new OAuthEvents
         {
             OnCreatingTicket = OnCreatingTicketGoogleCallback,
             OnTicketReceived = OnTicketReceivedCallback
         };
      })
      .AddJwtBearer("JwtBearer", jwtBearerOptions =>
      {
         jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
         {
             ValidateIssuerSigningKey = true,
             IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("my_secret")),

             ValidateIssuer = true,
             ValidIssuer = "my-api",

             ValidateAudience = true,
             ValidAudience = "my-client",

             ValidateLifetime = true,

             ClockSkew = TimeSpan.FromMinutes(5)
        };
    });
}

2 个答案:

答案 0 :(得分:8)

通常,JWT的声明会自动添加到ClaimsIdentity。

来源:
https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/blob/af5e5c2b0100e8348c63e2d2bb45612e2080841e/src/System.IdentityModel.Tokens.Jwt/JwtSecurityTokenHandler.cs#L1110)。

所以你应该能够使用&#39;用户&#39;基地的财产&#39;控制器&#39;类。

public async Task<IActionResult> Get()
{
    // TODO Move 'Claims' extraction code to an extension method
    var address = User.Claims.Where('GET THE NEEDED CLAIM');
    ...
}

从JWT令牌获取声明我从未遇到任何问题。 但到目前为止我只使用了 IdentityServer4.AccessTokenValidation 。但在内部它使用Microsoft JWT Handler afaik。

答案 1 :(得分:0)

无法发表评论,因为我的帖子篇幅太长了,所以改为发表单独的帖子。

如果您遵循发布的指南/链接ErazerBrecht,则索赔确实存储在ClaimsPrincipal用户中。我创建了一种扩展方法来检索声明。

请注意,我使用枚举来注册我的索赔。我使用词典将声明传递给生成令牌的方法,因此声明密钥应始终是唯一的。

扩展方法:

public static string GetClaim(this ClaimsPrincipal claimsPrincipal, JwtClaim jwtClaim)
{
  var claim = claimsPrincipal.Claims.Where(c => c.Type == jwtClaim.ToString()).FirstOrDefault();

  if (claim == null)
  {
      throw new JwtClaimNotFoundException(jwtClaim);
  }

  return claim.Value;
}

这样称呼:

var userId = User.GetClaim(JwtClaim.UserId);