如果从[授权]重定向到帐户/登录,oauth会出现CORS问题 [英] CORS issue with oauth if redirected to Account/Login from [Authorized]
问题描述
public class AccountController : Controller
{
public IActionResult Login(string returnUrl)
{
return new ChallengeResult(
GoogleDefaults.AuthenticationScheme,
new AuthenticationProperties
{
RedirectUri = Url.Action(nameof(LoginCallback), new { returnUrl })
});
}
...
我有上面显示的控制器.如果我在浏览器地址栏中输入 https://localhost:44378/Account/Login
,则可以正常工作-我被重定向到Google授权页面,但是如果我通过点击 [Authorize]
或另一个端点上的类似属性,出现以下错误:
I have the controller shown above. If I type https://localhost:44378/Account/Login
in the browser address bar it works fine - I get redirected to the Google authorization page but if I get redirected to this endpoint by hitting [Authorize]
or a similar attribute on another endpoint I'm getting error like the following one:
在以下位置访问XMLHttpRequest"https://accounts.google.com/o/oauth2/v2/auth?..."(重定向自来源的'https://localhost:44378/api/some-action')"http://localhost:3000"已被CORS策略阻止:对预检请求未通过访问控制检查:否请求中存在"Access-Control-Allow-Origin"标头资源.
Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/auth?...' (redirected from 'https://localhost:44378/api/some-action') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
JIC,我在应用程序注册Google页面中为授权的JavaScript起源和授权的重定向URI 添加了 http://localhost:3000
JIC, I added http://localhost:3000
to both Authorized JavaScript origins and Authorized redirect URIs in the app registration Google page.
为什么以及如何解决呢?
Why so and how to solve it?
网络:
我在同一端口上创建了具有前端和后端的测试项目,问题仍然存在
I created test project with frontend and backend on the same port, the issue persists
(从"https://localhost:44336/weatherforecast"(从"https://localhost:44336/weatherforecast"重定向))已被CORS政策阻止
(redirected from 'https://localhost:44336/weatherforecast') from origin 'https://localhost:44336' has been blocked by CORS policy
推荐答案
在Startup.cs文件中尝试使用此方法.
Try with this in your Startup.cs file.
this in the class->只读字符串MyAllowSpecificOrigins ="_myAllowSpecificOrigins";
this inside the class -> readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
,并在ConfigureServices方法中
and this inside the ConfigureServices method
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:4200");
});
});
用您的地址和端口更改
您也可以检查此链接: https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-5.0
you can check this link as well: https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0
这篇关于如果从[授权]重定向到帐户/登录,oauth会出现CORS问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!