首页 > 解决方案 > .Net Core 2.1 CORS 和 Firebase JWT 授权

问题描述

我正在关注这篇关于使用 .net Core 2 https://blog.markvincze.com/secure-an-asp-net-core-api-with-firebase/进行身份验证的博客文章

(我意识到我正在使用.net core 2.1,但认为它必须相似)

我正在使用带有 .net core 2.1 WebApi 后端的 React 前端。

我可以毫无问题地点击控制器,但是一旦我尝试将身份验证添加到 startup.cs,我就会得到:跨域请求被阻止:同源策略不允许在 localhost:4000 读取远程资源(原因:CORS请求不成功)

在那之前工作得很好

我的请求来自http://localhost:3000

更新 - - - - - - - - - - - - - - - - - - - - - - - - - -----------------

作为旁注,这在使用 POSTMAN 时有效。我可以通过 Firebase 进行身份验证并毫无问题地点击控制器

也适用于铬。好像是firefox浏览器的问题

我的实现(在成功的 Firebase 登录前端之后)

Axios 请求

axois
.get("https://localhost:4000/v1/picture", {
  headers: {
    accept: "application/json",
    "Accept-Language": "en-US,en;q=0.8",
    "Content-Type": `multipart/form-data;`,
    Authorization: "Bearer " + localStorage.getItem("token") 
    //Is the above the correct way to pass a jwt to be authenticated backend? This is the full jwt returned by Firebase
  }
})

启动.cs

services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                    builder => builder.WithOrigins("http://localhost:3000")
                        .AllowAnyMethod()
                        .AllowAnyHeader());
            }
        );

        //https://blog.markvincze.com/secure-an-asp-net-core-api-with-firebase/
        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.Authority = "https://securetoken.google.com/mafirebaseapp";
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = "https://securetoken.google.com/mafirebaseapp",
                    ValidateAudience = true,
                    ValidAudience = "mafirebaseapp",
                    ValidateLifetime = true
                };
            });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
...

...
        app.UseCors("AllowSpecificOrigin");
        app.UseAuthentication();
        app.UseHttpsRedirection();
        app.UseMvc();
}

图片控制器.cs

[Route("v1/picture")]
public class PictureController : Controller
{
    [Authorize]
    [HttpGet]
    public IActionResult GetPicture()
    {
        return Ok("Hi");
    }
}

我查看了另一篇文章,该文章指出方法的顺序有所不同,所以我认为这不是问题。

任何帮助都感激不尽!

谢谢!

标签: c#firebase.net-corefirebase-authenticationasp.net-core-webapi

解决方案


您可以尝试为特定操作使用指定 CORS 策略,只需添加[EnableCors("AllowSpecificOrigin")]到您的操作即可。


推荐阅读