title: Get userId from JWT on all Controller methods?
body: <p>I am creating a Core 2.0 Web API project that uses JWT for authentication and authorization. My controller methods that I want to secure are all decorated with the <code>Authorize</code> attribute.</p>
  
  <p>This is working. If I pass the JWT in the Bearer header, I get a 200. If I fail to pass the JWT, I get the 401. All working. In my JWT, I have stored the User ID in the 'UserId' field when authorizing..</p>
  
  <pre><code>var claimsdata = new[] {
                      new Claim("UserId", user.Id.ToString()),
  </code></pre>
  
  <p>I then have an extension method:</p>
  
  <pre><code>public static string GetUserId(this IPrincipal user)
          {
              if (user == null)
                  return string.Empty;
  
              var identity = (ClaimsIdentity)user.Identity;
              IEnumerable&lt;Claim&gt; claims = identity.Claims;
              return claims.FirstOrDefault(s =&gt; s.Type == "UserId")?.Value;
          }
  </code></pre>
  
  <p>On my controller method, with 'Authorize', I often need the ID of the user. So I call my GetUserId method. This works. However, I am unsure if this is the best way to get the Id from the token.</p>
  
  <pre><code>int.TryParse(User.GetUserId(), out _userId);
  </code></pre>
  
  <p>I need to use that code on all controllers. I can't do it in the constructor, as .. that's wrong I think.</p>
  
  <p>Am I doing the right thing here?</p>