title: How use a JWT token to retrieve current user data in .NET Core API?
body: <p>I have implemented JWT tokens to know who the current user is in an API application that is being used by an MVC controller.
  I'm building something like a forum app. The user must be logged in to be able to post, so I'm basically trying to use the JWT token to store the current user's email.
  When the user click on &quot;Create Post&quot; the action should get the token and its value, the problem is that I don't know how to use the token to protect controllers or retrieve data from current user, I have already copied and pasted the token in jwt.io to check if the data is stored correctly in the token and the value (the user's email) is stored correctly.</p>
  <p>The API controller with the &quot;login&quot; action:</p>
  <pre><code>    public async Task&lt;IActionResult&gt; login([FromBody] Usuario model)
      {
                  //check if user exists and the password is correct
  
                  //generates the token
                      var SecretKey = config.GetValue&lt;string&gt;(&quot;SecretKey&quot;);
                      var key = Encoding.ASCII.GetBytes(SecretKey);
  
                      var claims = new ClaimsIdentity(new Claim[] 
                      {
                          new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                          new Claim(ClaimTypes.Name, user.Mail)
                      });
                      claims.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Mail));
  
                      var tokenDesc = new SecurityTokenDescriptor
                      {
                          Subject = claims,
                          Expires = DateTime.UtcNow.AddMinutes(20),
                          SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                      };
  
                      var tokenHandler = new JwtSecurityTokenHandler();
                      var createdToken = tokenHandler.CreateToken(tokenDesc);
  
                      string bearer_token = tokenHandler.WriteToken(createdToken);
  
                      using(var client = new HttpClient())
                      {
                          client.DefaultRequestHeaders.Add(&quot;Authorization&quot;, &quot;Bearer&quot; + bearer_token);
                      }
  
                      return Ok(bearer_token);
                  }
      }
  </code></pre>
  <p>The MVC controller from where the API is used:</p>
  <pre><code>    public async Task&lt;IActionResult&gt; login(Usuario model)
      {
              HttpClient hc = new HttpClient();
              hc.BaseAddress = new Uri(&quot;https://localhost:44325/api/Usuarios/&quot;);
  
              var login = await hc.PostAsJsonAsync&lt;Usuario&gt;(&quot;login&quot;, model);
  
              //check the response
  
              var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
              identity.AddClaim(new Claim(ClaimTypes.Name, model.Email));
  
              var principal = new ClaimsPrincipal(identity);
  
              await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
  
              HttpContext.Session.SetString(&quot;JWToken&quot;, login.ToString());
  
              hc.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(&quot;Bearer&quot;, login.ToString());
  
              return RedirectToAction(&quot;IndexForumList&quot;, &quot;ForumControllerMVC&quot;);
          }
      }
  </code></pre>
  <p>This is the API method to &quot;Create Posts&quot; and where the token should be used, here the <code>userId</code> is null:</p>
  <pre><code>    public async Task&lt;IActionResult&gt; createPost([FromForm]ForumModel model)
      {
          string userId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
          
          //retrieves the current user email, validates and save the content to database
          
      }
  </code></pre>
  <p>And this is the MVC method to &quot;Create Posts&quot;:</p>
  <pre><code>public async Task&lt;IActionResult&gt; createPost(ForumModel model)
      {
          HttpClient hc = new HttpClient();
          hc.BaseAddress = new Uri(&quot;https://localhost:44325/api/Usuarios/&quot;);
  
          //var userPost = hc.PostAsJsonAsync&lt;ForumModel&gt;(&quot;Usuarios/createPost&quot;, model);
  
          var userPost = await hc.PostAsync(&quot;createPost&quot;, formContent);
  
          if(userPost.IsSuccessStatusCode == true)
          {
              return RedirectToAction(&quot;IndexForumList&quot;, &quot;ForoControllerMVC&quot;);
          }
      }
  </code></pre>
  <p>I have been suffering with this due to my lack of knowledge about JWT, any help is appreciated.</p>
  <p><strong>UPDATE</strong></p>
  <p>The <code>startup.cs</code></p>
  <pre><code>public void ConfigureServices(IServiceCollection services)
      {
          var key = Encoding.ASCII.GetBytes(Configuration.GetValue&lt;string&gt;(&quot;SecretKey&quot;));
  
          services.AddAuthentication(x =&gt;
          {
              x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
              x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
          }).AddJwtBearer(x =&gt;
          {
              x.RequireHttpsMetadata = false;
              x.SaveToken = true;
              x.TokenValidationParameters = new TokenValidationParameters
              {
                  ValidateIssuerSigningKey = true,
                  IssuerSigningKey = new SymmetricSecurityKey(key),
                  ValidateIssuer = false,
                  ValidateAudience = false
              };
          });
          services.AddSession(
              options =&gt;
              {
                  options.IdleTimeout = TimeSpan.FromMinutes(10);
                  options.Cookie.HttpOnly = true;
                  options.Cookie.IsEssential = true;
              });
      }
  </code></pre>