首页 > 解决方案 > 谷歌在 Angular 7 中使用 .NET Core API 登录

问题描述

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

从源“null”访问'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# 代码

启动.cs

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;
    };
});

AuthenticationController.cs

[HttpGet]
public IActionResult ExternalLogin(string provider)
{
    var callbackUrl = Url.Action("ExternalLoginCallback");
    var authenticationProperties = new AuthenticationProperties { RedirectUri = callbackUrl };
    return this.Challenge(authenticationProperties, provider);
}

[HttpGet]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
{
    var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);

    return this.Ok(new
    {
        NameIdentifier = result.Principal.FindFirstValue(ClaimTypes.NameIdentifier),
        Email = result.Principal.FindFirstValue(ClaimTypes.Email),
        Picture = result.Principal.FindFirstValue("image")
    });
}

角码

login.component.html

<button (click)="googleLogIn()">Log in with Google</button>

登录组件.ts

googleLogIn() {
  this.authenticationService.loginWithGoogle()
  .pipe(first())
  .subscribe(
    data => console.log(data)
  );
}

身份验证.service.ts

public loginWithGoogle() {
  return this.http.get<any>(`${environment.api.apiUrl}${environment.api.authentication}externalLogin`,
  {
    params: new HttpParams().set('provider', 'Google'),
    headers: new HttpHeaders()
      .set('Access-Control-Allow-Headers', 'Content-Type')
      .set('Access-Control-Allow-Methods', 'GET')
      .set('Access-Control-Allow-Origin', '*')
  })
  .pipe(map(data => {
    return data;
  }));
}

我想像以下方案: Angular -> My API -> redirect to Google -> google return user data to my api -> My API return JWT token -> Angular use token

你能帮我解决这个问题吗?

标签: angularasp.net-web-apiasp.net-corecorsgoogle-authentication

解决方案


问题似乎是,尽管服务器正在发送 302 响应(url 重定向),Angular 正在发出 XMLHttpRequest,但它没有重定向。遇到这个问题的人越来越多...

对我来说,试图在前端拦截响应以进行手动重定向或更改服务器上的响应代码(这是一个“挑战”响应......)不起作用。

因此,我所做的就是在 Angular 中将 window.location 更改为后端服务,以便浏览器可以管理响应并正确进行重定向。

注意:在文章的最后,我解释了一个更直接的 SPA 应用程序解决方案,无需使用 cookie 或 AspNetCore 身份验证。

完整的流程是这样的:

(1) Angular 将浏览器位置设置为 API -> (2) API 发送 302 响应 -> (3) 浏览器重定向到 Google -> (4) Google 将用户数据作为 cookie 返回给 API -> (5) API 返回 JWT令牌 -> (6) Angular 使用令牌

1.- Angular 将浏览器位置设置为 API。我们将提供程序和 returnURL 传递给我们希望 API 在流程结束时返回 JWT 令牌的位置。

import { DOCUMENT } from '@angular/common';
...
 constructor(@Inject(DOCUMENT) private document: Document, ...) { }
...
  signInExternalLocation() {
    let provider = 'provider=Google';
    let returnUrl = 'returnUrl=' + this.document.location.origin + '/register/external';

    this.document.location.href = APISecurityRoutes.authRoutes.signinexternal() + '?' + provider + '&' + returnUrl;
  }

2.- API 发送 302 挑战响应。我们使用提供者和我们希望谷歌给我们回电的 URL 创建重定向。

// GET: api/auth/signinexternal
[HttpGet("signinexternal")]
public IActionResult SigninExternal(string provider, string returnUrl)
{
    // Request a redirect to the external login provider.
    string redirectUrl = Url.Action(nameof(SigninExternalCallback), "Auth", new { returnUrl });
    AuthenticationProperties properties = _signInMgr.ConfigureExternalAuthenticationProperties(provider, redirectUrl);

    return Challenge(properties, provider);
}

5.- API 接收谷歌用户数据并返回 JWT 令牌。在查询字符串中,我们将获得 Angular 返回 URL。在我的情况下,如果用户未注册,我正在做一个额外的步骤来请求许可。

// GET: api/auth/signinexternalcallback
[HttpGet("signinexternalcallback")]
public async Task<IActionResult> SigninExternalCallback(string returnUrl = null, string remoteError = null)
{
    //string identityExternalCookie = Request.Cookies["Identity.External"];//do we have the cookie??

    ExternalLoginInfo info = await _signInMgr.GetExternalLoginInfoAsync();

    if (info == null)  return new RedirectResult($"{returnUrl}?error=externalsigninerror");

    // Sign in the user with this external login provider if the user already has a login.
    Microsoft.AspNetCore.Identity.SignInResult result = 
        await _signInMgr.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);

    if (result.Succeeded)
    {
        CredentialsDTO credentials = _authService.ExternalSignIn(info);
        return new RedirectResult($"{returnUrl}?token={credentials.JWTToken}");
    }

    if (result.IsLockedOut)
    {
        return new RedirectResult($"{returnUrl}?error=lockout");
    }
    else
    {
        // If the user does not have an account, then ask the user to create an account.

        string loginprovider = info.LoginProvider;
        string email = info.Principal.FindFirstValue(ClaimTypes.Email);
        string name = info.Principal.FindFirstValue(ClaimTypes.GivenName);
        string surname = info.Principal.FindFirstValue(ClaimTypes.Surname);

        return new RedirectResult($"{returnUrl}?error=notregistered&provider={loginprovider}" +
            $"&email={email}&name={name}&surname={surname}");
    }
}

注册额外步骤的 API(对于此调用,Angular 必须使用“WithCredentials”发出请求才能接收 cookie):

[HttpPost("registerexternaluser")]
public async Task<IActionResult> ExternalUserRegistration([FromBody] RegistrationUserDTO registrationUser)
{
    //string identityExternalCookie = Request.Cookies["Identity.External"];//do we have the cookie??

    if (ModelState.IsValid)
    {
        // Get the information about the user from the external login provider
        ExternalLoginInfo info = await _signInMgr.GetExternalLoginInfoAsync();

        if (info == null) return BadRequest("Error registering external user.");

        CredentialsDTO credentials = await _authService.RegisterExternalUser(registrationUser, info);
        return Ok(credentials);
    }

    return BadRequest();
}

SPA 应用程序的不同方法:

就在我完成它的工作时,我发现对于 SPA 应用程序有更好的方法(https://developers.google.com/identity/sign-in/web/server-side-flow,Google JWT Authentication with AspNet Core 2.0https: //medium.com/mickeysden/react-and-google-oauth-with-net-core-backend-4faaba25ead0 )

对于这种方法,流程将是:

(1) Angular 打开 google 身份验证 -> (2) 用户身份验证 -> (3) Google 将 googleToken 发送到 Angular -> (4) Angular 将其发送到 API -> (5) API 对 google 进行验证并返回 JWT 令牌-> (6) Angular 使用令牌

为此,我们需要在 Angular 中安装“ angularx-social-login ”npm 包,在 netcore 后端安装“ Google.Apis.Auth ”NuGet 包

1. 和 4. - Angular 打开 google 身份验证。我们将使用 angularx-social-login 库。用户在Angular 中唱歌后,将 googletoken 发送到 API

login.module.ts我们添加:

let config = new AuthServiceConfig([
  {
    id: GoogleLoginProvider.PROVIDER_ID,
    provider: new GoogleLoginProvider('Google ClientId here!!')
  }
]);

export function provideConfig() {
  return config;
}

@NgModule({
  declarations: [
...
  ],
  imports: [
...
  ],
  exports: [
...
  ],
  providers: [
    {
      provide: AuthServiceConfig,
      useFactory: provideConfig
    }
  ]
})

在我们的login.component.ts上:

import { AuthService, GoogleLoginProvider } from 'angularx-social-login';
...
  constructor(...,  private socialAuthService: AuthService)
...

  signinWithGoogle() {
    let socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;
    this.isLoading = true;

    this.socialAuthService.signIn(socialPlatformProvider)
      .then((userData) => {
        //on success
        //this will return user data from google. What you need is a user token which you will send it to the server
        this.authenticationService.googleSignInExternal(userData.idToken)
          .pipe(finalize(() => this.isLoading = false)).subscribe(result => {

            console.log('externallogin: ' + JSON.stringify(result));
            if (!(result instanceof SimpleError) && this.credentialsService.isAuthenticated()) {
              this.router.navigate(['/index']);
            }
        });
      });
  }

在我们的authentication.service.ts上:

  googleSignInExternal(googleTokenId: string): Observable<SimpleError | ICredentials> {

    return this.httpClient.get(APISecurityRoutes.authRoutes.googlesigninexternal(), {
      params: new HttpParams().set('googleTokenId', googleTokenId)
    })
      .pipe(
        map((result: ICredentials | SimpleError) => {
          if (!(result instanceof SimpleError)) {
            this.credentialsService.setCredentials(result, true);
          }
          return result;

        }),
        catchError(() => of(new SimpleError('error_signin')))
      );

  }

5.- API 对 google 进行验证并返回 JWT 令牌。我们将使用“Google.Apis.Auth”NuGet 包。我不会为此提供完整代码,但请确保在验证 de 令牌时将受众添加到安全登录设置中:

 private async Task<GoogleJsonWebSignature.Payload> ValidateGoogleToken(string googleTokenId)
    {
        GoogleJsonWebSignature.ValidationSettings settings = new GoogleJsonWebSignature.ValidationSettings();
        settings.Audience = new List<string>() { "Google ClientId here!!" };
        GoogleJsonWebSignature.Payload payload = await GoogleJsonWebSignature.ValidateAsync(googleTokenId, settings);
        return payload;
    }

推荐阅读