title: Cannot get current user or authorize
body: <p>Working on an Angular 2/ASP.NET Core 2.1 app. Upon logging in, I can console.log the JWT token from the front-end, but when I try to access a controller (AccountsController.cs) with an <code>[Authorize]</code> attribute, I get a 401 error. If I remove the attribute, and I try to get the current user using <code>var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);</code> I get sent immediately back to the front-end and receive an error message via the resolver.</p>
  
  <p>It seems that the current user data is not being sent to the back-end with the request. Or it's not being stored? Or maybe I'm not accessing it correctly?
  <br><br>
  <strong>account-list.resolver.ts</strong></p>
  
  <pre><code>import { Resolve, Router, ActivatedRouteSnapshot } from '@angular/router';
  import { Account } from '../../_models/account';
  import { Injectable } from '@angular/core';
  import { AccountService } from '../../_services/account.service';
  import { AlertifyService } from '../../_services/alertify.service';
  import { Observable } from 'rxjs/Observable';
  import 'rxjs/add/observable/of';
  import 'rxjs/add/operator/catch';
  
  @Injectable()
  export class AccountListResolver implements Resolve&lt;Account[]&gt; {
    pageSize = 5;
    pageNumber = 1;
  
    constructor(private accountService: AccountService,
      private router: Router,
      private alertify: AlertifyService) {
    }
  
    resolve(route: ActivatedRouteSnapshot): Observable&lt;Account[]&gt; {
      return this.accountService.getAccounts(this.pageNumber, this.pageSize).catch(error =&gt; {
        this.alertify.error('Problem retrieving data');
        this.router.navigate(['/dashboard']);
        return Observable.of(null);
      });
    }
  }
  </code></pre>
  
  <p><br>
  <strong>account.service.ts</strong></p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import { environment } from '../../environments/environment';
  import { Account } from '../_models/account';
  import 'rxjs/add/operator/map';
  import 'rxjs/add/operator/catch';
  import 'rxjs/add/observable/throw';
  import { PaginatedResult } from '../_models/pagination';
  import { HttpClient, HttpParams } from '@angular/common/http';
  
  @Injectable()
  export class AccountService {
    baseUrl = environment.apiUrl;
  
    constructor(private authHttp: HttpClient) { }
  
    getAccounts(page?, itemsPerPage?, accountParams?: any) {
      const paginatedResult: PaginatedResult&lt;Account[]&gt; = new PaginatedResult&lt;Account[]&gt;();
      let params = new HttpParams();
  
      if (page != null &amp;&amp; itemsPerPage != null) {
        params = params.append('pageNumber', page);
        params = params.append('pageSize', itemsPerPage);
      }
  
      // if (accountParams != null) {
      //   params = params.append('paramName', accountParams.paramName);
      // }
  
      return this.authHttp
        .get&lt;Account[]&gt;(this.baseUrl + 'accounts', { observe: 'response', params })
        .map(response =&gt; {
          paginatedResult.result = response.body;
          if (response.headers.get('Pagination') != null) {
            paginatedResult.pagination = JSON.parse(response.headers.get('Pagination'));
          }
  
          return paginatedResult;
        });
    }
  }
  </code></pre>
  
  <p><br>
  <strong>AccountsController</strong></p>
  
  <pre><code>[Authorize]
  [Route("api/[controller]")]
  public class AccountsController : Controller
  {
      private readonly IBaseRepository _repo;
      private readonly IMapper _mapper;
  
      public AccountsController(IBaseRepository repo, IMapper mapper)
      {
          _mapper = mapper;
          _repo = repo;
      }
  
      [HttpGet]
      public async Task&lt;IActionResult&gt; GetAccounts([FromQuery] AccountParams accountParams)
      {
          var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
          //^^^WHERE IT BREAKS WHEN AUTHORIZATION ATTRIBUTE IS REMOVED
  
          //code to generate list of accounts to return
          accountParams.UserId = currentUserId;
  
          var accounts = await _repo.GetAccounts(accountParams);
  
          var accountsToReturn = _mapper.Map&lt;IEnumerable&lt;AccountForListDto&gt;&gt;(accounts);
  
          Response.AddPagination(accounts.CurrentPage, accounts.PageSize, accounts.TotalCount, accounts.TotalPages);
  
          return Ok(accountsToReturn);
      }
  }
  </code></pre>
  
  <p><br></p>
  
  <h3>**EDIT**</h3>
  
  <p><strong>Startup.cs</strong></p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services)
  {
      var key = Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value);
  
      services.AddDbContext&lt;DataContext&gt;(x =&gt; x
          .UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b =&gt;
              b.MigrationsAssembly(("MyApp.App")))
          .ConfigureWarnings(warnings =&gt; warnings.Ignore(CoreEventId.IncludeIgnoredWarning)));
  
      services.AddMvc()
          .AddJsonOptions(opt =&gt;
          {
              opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
          })
          .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  
      services.AddSpaStaticFiles(configuration =&gt; { configuration.RootPath = "ClientApp/dist"; });
  
      services.AddTransient&lt;Seed&gt;();
  
      services.AddCors();
  
      services.AddAutoMapper();
  
      services.AddScoped&lt;IAuthRepository, AuthRepository&gt;();
  
      services.AddScoped&lt;IBaseRepository, BaseRepository&gt;();
  
      services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .AddJwtBearer(options =&gt;
          {
              options.TokenValidationParameters = new TokenValidationParameters
              {
                  ValidateIssuerSigningKey = true,
                  IssuerSigningKey = new SymmetricSecurityKey(key),
                  ValidateIssuer = false,
                  ValidateAudience = false
              };
          });
  
      services.AddScoped&lt;LogUserActivity&gt;();
  }
  
  public void ConfigureDevelopmentServices(IServiceCollection services)
  {
      var key = Encoding.ASCII.GetBytes(Configuration.GetSection("AppSettings:Token").Value);
  
      services.AddDbContext&lt;DataContext&gt;(x =&gt; x
          .UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b =&gt;
              b.MigrationsAssembly(("MyApp.App")))
          .ConfigureWarnings(warnings =&gt; warnings.Ignore(CoreEventId.IncludeIgnoredWarning)));
  
      services.AddMvc()
          .AddJsonOptions(opt =&gt;
          {
              opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
          })
          .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  
      services.AddSpaStaticFiles(configuration =&gt; { configuration.RootPath = "ClientApp/dist"; });
  
      services.AddTransient&lt;Seed&gt;();
  
      services.AddCors();
  
      services.AddAutoMapper();
  
      services.AddScoped&lt;IAuthRepository, AuthRepository&gt;();
  
      services.AddScoped&lt;IBaseRepository, BaseRepository&gt;();
  
      services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
          .AddJwtBearer(options =&gt;
          {
              options.TokenValidationParameters = new TokenValidationParameters
              {
                  ValidateIssuerSigningKey = true,
                  IssuerSigningKey = new SymmetricSecurityKey(key),
                  ValidateIssuer = false,
                  ValidateAudience = false
              };
          });
  
      services.AddScoped&lt;LogUserActivity&gt;();
  }
  
  public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
      if (env.IsDevelopment())
      {
          app.UseDeveloperExceptionPage();
      }
      else
      {
          app.UseExceptionHandler(builder =&gt;
          {
              builder.Run(async context =&gt;
              {
                  context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
  
                  var error = context.Features.Get&lt;IExceptionHandlerFeature&gt;();
                  if (error != null)
                  {
                      context.Response.AddApplicationError(error.Error.Message);
                      await context.Response.WriteAsync(error.Error.Message);
                  }
              });
          });
      }
  
      app.ConfigureSwagger(Assembly.GetExecutingAssembly());
  
      app.UseCors(x =&gt; x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
      app.UseDefaultFiles();
      app.UseHttpsRedirection();
      app.UseStaticFiles();
  
      app.UseSpaStaticFiles();
  
      app.UseMvc(routes =&gt;
      {
          routes.MapRoute(
              name: "default",
              template: "{controller}/{action=Index}/{id?}");
      });
  
      app.UseSpa(spa =&gt;
      {
          // To learn more about options for serving an Angular SPA from ASP.NET Core,
          // see https://go.microsoft.com/fwlink/?linkid=864501
  
          spa.Options.SourcePath = "ClientApp";
  
          if (env.IsDevelopment())
          {
              spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
              //spa.UseAngularCliServer(npmScript: "start");
          }
      });
  }
  </code></pre>