【问题标题】:cant access JWT token because of CORS using .NetCore由于使用 .Net Core 的 CORS,无法访问 JWT 令牌
【发布时间】:2020-08-12 18:50:36
【问题描述】:

我的应用程序后端有一个非常奇怪的问题,这是我的启动:

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);       
        string securityKey = "My_First_Key_generated_by_myself";
        var semetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));
        services.AddCors(options =>
        {
            options.AddPolicy(
              "EnableCORS",
              builder => builder.AllowAnyOrigin()
              .AllowAnyMethod()
              .AllowAnyHeader()
              .AllowCredentials().Build());
        });
        services.AddAuthentication().AddJwtBearer(
            options =>
            {

                options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {

                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = "morteza",
                    ValidAudience = "pass",
                    IssuerSigningKey = semetricSecurityKey


                };


            }
            );


    }

    // 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();
        }
        app.UseAuthentication();

        //app.UseHttpsRedirection();
        app.UseCors("EnableCORS");

        app.UseMvc();
    }

我的Athentication Controller生成Token:

  [HttpPost("token")]
  //  [Authorize]
    public ActionResult GetToken(string username)
    {
        //  return Ok("hi Morteza");
        if (username == "morteza") { 
        string securityKey = "My_First_Key_generated_by_myself";
        var semetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(securityKey));

        var claims = new List<Claim>();
        claims.Add(new Claim(ClaimTypes.Role, "Admin"));


        var signIncredentials = new SigningCredentials(semetricSecurityKey, SecurityAlgorithms.HmacSha256Signature);
        var token = new JwtSecurityToken(
            issuer: "morteza",
            audience: "pass",
            expires: DateTime.Now.AddHours(1),
            claims: claims,
            signingCredentials: signIncredentials);



        return Ok(new JwtSecurityTokenHandler().WriteToken(token));
    }

            else
        {

            return null;
        }

        }

我不知道为什么我从源“http://localhost:4200”获得对 XMLHttpRequest 的访问权限已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头当我在前端使用它时?

【问题讨论】:

    标签: asp.net-core jwt asp.net-core-webapi


    【解决方案1】:

    您需要在app.UseAuthentication() 之前调用app.UseCors(),因为您的代码目前正在尝试在应用CORS 策略之前进行身份验证。

    您的Configure 方法应如下所示:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        // Moved this line 
        app.UseCors("EnableCORS");
    
        app.UseAuthentication();
    
        //app.UseHttpsRedirection();
    
        app.UseMvc();
    }
    

    See the documentation on middleware order and recommended order for common services

    【讨论】:

      猜你喜欢
      • 2019-05-11
      • 2018-04-26
      • 1970-01-01
      • 2019-01-21
      • 2017-10-23
      • 2018-07-18
      • 2019-04-15
      • 2023-03-16
      • 2018-10-07
      相关资源
      最近更新 更多