title: Reading JWT Token from API in ASP.NET Core
body: <p>My setup: I've created and have running a WebAPI solution that performs the authentication of a username and password against a source (currently a db). This generates the JWT token and returns it to the requesting app (a ASP.NET Core 2.2 app).  </p>
  
  <p>Most solutions talk of securing the WebAPI exposed methods but my approach is to only do the authentication through WebAPI.  The individual apps need to accept the token so they can determine authorization. </p>
  
  <p>Now the question: what is the best approach to reading the token from the WebAPI (which I've done already), validating it, and then storing it for any/all controllers to know there is an authenticated user (via Authorize attribute) so long as the token is valid? </p>
  
  <p>Debugging this more, it seems my token is not being added to the headers. I see this debug message:</p>
  
  <blockquote>
    <p>Authorization failed for the request at filter 'Microsoft.AspNet.Mvc.Filters.AuthorizeFilter'</p>
  </blockquote>
  
  <p><strong>Code Update2</strong> - code that gets the JWT:</p>
  
  <pre class="lang-cs prettyprint-override"><code>        var client = _httpClientFactory.CreateClient();
          client.BaseAddress = new Uri(_configuration.GetSection("SecurityApi:Url").Value);
          client.DefaultRequestHeaders.Accept.Clear();
          client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  
          //login
          Task&lt;HttpResponseMessage&gt; response = ValidateUserAsync(client, username, password);
          Task&lt;Core.Identity.TokenViewModel&gt; tokenResult = response.Result.Content.ReadAsAsync&lt;Core.Identity.TokenViewModel&gt;();
  
          if (!response.Result.IsSuccessStatusCode)
          {
              if (tokenResult != null &amp;&amp; tokenResult.Result != null)
              {
                  ModelState.AddModelError("", tokenResult.Result.ReasonPhrase);
              }
              else
              {
                  ModelState.AddModelError("", AppStrings.InvalidLoginError);
              }
              return View();
          }
  
          JwtSecurityToken token = new JwtSecurityToken(tokenResult.Result.Token);
          int userId;
  
          if (int.TryParse(token.Claims.First(s =&gt; s.Type == JwtRegisteredClaimNames.NameId).Value, out userId))
          {
              //load app claims
              Core.Identity.UserInfo userInfo = Core.Identity.UserLogin.GetUser(_identityCtx, userId);
              Core.Identity.UserStore uStore = new Core.Identity.UserStore(_identityCtx);
              IList&lt;Claim&gt; claims = uStore.GetClaimsAsync(userInfo, new System.Threading.CancellationToken(false)).Result;
              claims.Add(new Claim(Core.Identity.PowerFleetClaims.PowerFleetBaseClaim, Core.Identity.PowerFleetClaims.BaseUri));
  
              ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims, JwtBearerDefaults.AuthenticationScheme);
              ClaimsPrincipal principal = new ClaimsPrincipal(claimsIdentity);
  
              //complete
              AuthenticationProperties authProperties = new AuthenticationProperties();
              authProperties.ExpiresUtc = token.ValidTo;
              authProperties.AllowRefresh = false;
              authProperties.IsPersistent = true;
  
              client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(JwtBearerDefaults.AuthenticationScheme, tokenResult.Result.Token);
              //var stuff = HttpContext.SignInAsync(JwtBearerDefaults.AuthenticationScheme, principal, authProperties);
          }
          else
          {
              ModelState.AddModelError("", AppStrings.InvalidLoginError);
              return View();
          }
  
          return RedirectToAction("Index", "Home");
  </code></pre>
  
  <p>Startup:</p>
  
  <pre><code>private void ConfigureIdentityServices(IServiceCollection services)
      {
          services.ConfigureApplicationCookie(options =&gt; options.LoginPath = "/Login");
  
          //authentication token
          services.AddAuthentication(opt =&gt;
          {
              opt.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
              opt.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
          }).AddCookie(opt =&gt;
          {
              opt.LoginPath = "/Login";
              opt.LogoutPath = "/Login/Logoff";
              opt.Cookie.Name = Configuration.GetSection("SecurityApi:CookieName").Value;
          }).AddJwtBearer(options =&gt;
          {
              options.SaveToken = true;
              options.RequireHttpsMetadata = false;
  
              options.TokenValidationParameters = new TokenValidationParameters()
              {
                  ValidateAudience = true,
                  ValidAudience = Configuration.GetSection("SecurityApi:Issuer").Value,
                  ValidateIssuer = true,
                  ValidIssuer = Configuration.GetSection("SecurityApi:Issuer").Value,
                  ValidateIssuerSigningKey = true,
                  IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("SecurityApi:Key").Value)),
                  ValidateLifetime = true
              };
          });
  
          Core.Startup authStart = new Core.Startup(this.Configuration);
          authStart.ConfigureAuthorizationServices(services);
      }
  </code></pre>
  
  <p>Auth:</p>
  
  <pre><code>public void ConfigureAuthorizationServices(IServiceCollection services)
      {
          services.AddDbContext&lt;Identity.IdentityContext&gt;(options =&gt; options.UseSqlServer(Configuration.GetConnectionString("SecurityConn")));
          services.AddScoped&lt;DbContext, Identity.IdentityContext&gt;(f =&gt;
          {
              return f.GetService&lt;Identity.IdentityContext&gt;();
          });
  
          services.AddIdentityCore&lt;Identity.UserInfo&gt;().AddEntityFrameworkStores&lt;Identity.IdentityContext&gt;().AddRoles&lt;Identity.Role&gt;();
          services.AddTransient&lt;IUserClaimStore&lt;Core.Identity.UserInfo&gt;, Core.Identity.UserStore&gt;();
          services.AddTransient&lt;IUserRoleStore&lt;Core.Identity.UserInfo&gt;, Core.Identity.UserStore&gt;();
          services.AddTransient&lt;IRoleStore&lt;Core.Identity.Role&gt;, Core.Identity.RoleStore&gt;();
  
          services.AddAuthorization(auth =&gt;
          {
              auth.AddPolicy(JwtBearerDefaults.AuthenticationScheme, new AuthorizationPolicyBuilder().AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build());
              auth.AddPolicy(PFBaseClaim, policy =&gt; policy.RequireClaim(Identity.PFClaims.BaseUri));
          });
      }
  </code></pre>