小编tot*_*kov的帖子

使用.NET Core API在Angular 7中进行Google登录

我正在尝试在我的Angular应用程序中实现Google登录。如果我尝试为外部登录服务器调用api端点,则返回405错误代码,如下所示:

从源“空” 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=...'(从重定向'http://localhost:5000/api/authentication/externalLogin?provider=Google')对XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:所请求的资源上不存在“ Access-Control-Allow-Origin”标头。

如果我api/authentication/externalLogin?provider=Google在新的浏览器选项卡中调用,则所有功能均正常运行。我认为问题出在角度代码中。

我的api适用于localhost:5000。Angular应用程序可在上使用localhost:4200。我使用.net core 2.1和Angular 7

C#代码

启动文件

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = false,
        ValidateAudience = false
    };
})
.AddCookie()
.AddGoogle(options => {
    options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.ClientId = "xxx";
    options.ClientSecret = "xxx";
    options.Scope.Add("profile");
    options.Events.OnCreatingTicket = (context) =>
    {
        context.Identity.AddClaim(new Claim("image", context.User.GetValue("image").SelectToken("url").ToString()));

        return Task.CompletedTask;
    };
});
Run Code Online (Sandbox Code Playgroud)

AuthenticationController.cs

[HttpGet]
public IActionResult …
Run Code Online (Sandbox Code Playgroud)

google-authentication cors asp.net-web-api asp.net-core angular

6
推荐指数
1
解决办法
2221
查看次数