c# - .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");
}
}
我查看了另一篇文章,该文章指出方法的顺序有所不同,所以我认为这不是问题。
任何帮助都感激不尽!
谢谢!
解决方案
您可以尝试为特定操作使用指定 CORS 策略,只需添加[EnableCors("AllowSpecificOrigin")]
到您的操作即可。
推荐阅读
- node.js - 如何从 LoopBack 3 中的删除路由中获取访问令牌
- python - Python 访问和迭代包含列表的数据框中的值
- linux - 将变量传递给 BASH 函数时出现“找不到命令”,我是否引用不正确?
- android - Kotlin 将视频保存到图库
- anaconda - 创建 requirements.txt 文件以获取 MyBinder 链接以与 Github 共享
- ruby-on-rails - ArgumentError(不支持的参数类型:0(整数)):
- python - 想要使用 python 查找批量域的域年龄
- reactjs - 添加总价以反应购物车
- jquery - 单击搜索后,发送过滤器查询并在另一个页面上发布过滤器结果
- python - 'clientname' 对象没有属性 'set_password'