Javascript 授权Web Asp.Net核心JWT,8

Javascript 授权Web Asp.Net核心JWT,8,javascript,c#,angular,typescript,asp.net-core,Javascript,C#,Angular,Typescript,Asp.net Core,请指出问题所在。 我遇到的问题是我有一个添加了属性Authorize的控制器。因此,当我尝试访问actionResult GETDATA时,它会说找不到操作。但是如果删除属性Authorize,它将按预期工作。 因此,每次我发出请求时,我都会在头上添加一个jwt令牌。 以下是代码: **Angular 8 HttpInterceptor** const currentUser = this.authenticationService.currentUserValue; //if

请指出问题所在。 我遇到的问题是我有一个添加了属性Authorize的控制器。因此,当我尝试访问actionResult GETDATA时,它会说找不到操作。但是如果删除属性Authorize,它将按预期工作。 因此,每次我发出请求时,我都会在头上添加一个jwt令牌。 以下是代码:

**Angular 8 HttpInterceptor**

    const currentUser = this.authenticationService.currentUserValue;
    //if (currentUser && currentUser.authData) {
    if (currentUser && currentUser.Token) {
      debugger;
      request = request.clone({
        setHeaders: {
          Authorization: `Bearer ${currentUser.Token}`,
          CurrentTabID: `${currentUser.CurrentTabID}`
        }
      });
    }


**MyController**
    [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class PatientController : ControllerBase
    {
        [HttpGet("GetTestData")]
       //--These is the one i can't access
        public IActionResult GetTestData() 
        {
            return Ok("");
        }
        [AllowAnonymous]
        [HttpGet("GetTestDataOne")]
        public IActionResult GetTestDataOne()
        {
            return Ok("Hi John");
        }
    }
appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=.; Database=blah;persist security info=True;user id=blah;password=blah;"
  },
  "AllowedHosts": "*",
  "ApplicationSettings": {
    "Secret": "1234567890123456",
    "ClientURL": ""
  }
}
startup.cs

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddDbContext<PPMPBookingContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
        services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
        var key = Encoding.UTF8.GetBytes(Configuration["ApplicationSettings:Secret"].ToString());

        // configure strongly typed settings objects
        //var appSettingsSection = Configuration.GetSection("AppSettings");
        //services.Configure<AppSettings>(appSettingsSection);

        // In production, the Angular files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });


        services.AddAuthentication(x =>
        {
            x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(x =>
        {

            x.RequireHttpsMetadata = false;
            x.SaveToken = true;
            x.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidIssuer="vlad",
                ValidAudience="Client"

            };
        });
        // configure DI for application services
        services.AddScoped<IUserService, UserService>();
        services.AddScoped<IPracticeService, PracticeService>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseAuthentication();

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSpaStaticFiles();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");
        });

        app.UseSpa(spa =>
        {
            // 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.UseAngularCliServer(npmScript: "start");
            }
        });
    }

您确定JWT在标头中正确发送吗?代码在我看来很好。我最近实现了这个完全相同的模式,我遇到了一个问题,即JWT是为匿名用户生成的,因为逻辑是在auth进程完成之前运行的。这导致角度中的JWT与authroize过程中的预期JWT不匹配。那么也许也要检查一下?
public UserInfo Authenticate(int businessID, string username, string password)
        {

            // authentication successful so generate jwt token
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_config.GetSection("ApplicationSettings:Secret").Value);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.ID.ToString())
                }),
                Expires = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            userInfo.Token = tokenHandler.WriteToken(token);

            byte[] bytes = Encoding.GetEncoding(28591).GetBytes($"{businessID}{username}");
            userInfo.AuthData = System.Convert.ToBase64String(bytes);

            user.Password = null;
            userInfo.User = user;
            userInfo.BusinessID = businessID;
            userInfo.Practice = _practiceService.PracticeInfo(businessID);
            userInfo.CurrentTabID = Guid.NewGuid().ToString();
            return userInfo;
        }