Asp .Net5 与 Google Oauth2 重定向错误

问题描述 投票:0回答:1

我在实施 google oauth2 时遇到问题。 我遇到重定向不匹配的情况。

我在谷歌控制台中https://localhost:4200/signin-google

我的困惑是这样的。如果我在 google 控制台和 options.CallbackPath 中执行 https://localhost:4200/api/google/response 。然后我成功重定向了挑战,但 /api/google/response 在 google 的中间件身份验证期间永远不会触发。(我有各种不会打印的控制台)。它也很成功,因为我得到了一个带有我的谷歌信息(如姓名、电子邮件等)的cookie。

很多教程只是将 google 控制台设置为 https://localhost:4200/signin-google。他们从未设置过 options.CallbackPath 或任何 http:localhost/signin-google 路线,并且当我得到时他们成功播放 错误 400:redirect_uri_mismatch(这是正确的,因为我的应用程序没有 https://localhost:4200/signin-google)。

我是否应该在谷歌控制台上返回https://localhost:4200/api/google/response并将CallbackPath设置为/api/google/response并查看为什么它不触发?

我应该在我的应用程序上添加到 /singin-google 的路线吗?

为什么在许多没有路由和 CallbackPath 的教程中可以工作,而在我的情况下却不能?

提前谢谢您。

startup.cs

 public void ConfigureServices(IServiceCollection services)
 {
   // configurations
   services.Configure<EnvironmentVariables>(Configuration.GetSection(EnvironmentVariables.EnvironmentVariable));
   services.Configure<RabbitMQSettingsOptions>(Configuration.
    GetSection(RabbitMQSettingsOptions.RabbitMQSettings));

   services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
   .AddCookie(options =>
   {
     this.SetUpCookieAuthentication(options);
   });

   services.AddAuthentication().AddGoogle(options =>
   {
     this.SetUpGoogleAuthentication(options);
   });

   services.AddCors(options =>
   {
     this.SetUpCorsPolicy(options);
   });

  ...
 }
private void SetUpGoogleAuthentication(GoogleOptions options)
{
  ...
  // set GoogleOptions
  //options.CallbackPath = new PathString(path);
  options.ClientSecret = googleAuthentication.ClientSecret;
  options.ClientId = googleAuthentication.ClientId;
  
}

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
    if (env.IsDevelopment())
    {
      app.UseDeveloperExceptionPage();
    }
    //app.UseHttpsRedirection();

    app.UseRouting();

    app.UseCors("CorsPolicy");
    // app.UseSession();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseCookiePolicy();

    app.UseEndpoints(endpoints =>
    {
      endpoints.MapControllers();
    });
  }

GoogleController.cs

using AutoMapper.Internal;
using Domain.DDtos.Users;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using ServiceLayer.Dtos.Users;
using ServiceLayer.Interfaces;
using ServiceLayer.Services;
using ServiceLayer.Types;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Eshop.Controllers
{
  [Route("api/google")]
  [ApiController]
  public class GoogleController : ControllerBase
  {
    private IOptions<EnvironmentVariables> _envOptions;
    private readonly IEnvironmentVariableService _envService;
    private readonly IUserService _userService;

    public GoogleController(IOptions<EnvironmentVariables> envOptions,
      IEnvironmentVariableService envService, IUserService userService)
    {
      _envOptions = envOptions;
      _envService = envService;
      _userService = userService;
    }

    [HttpGet("signin")]
    public async Task<ActionResult> GetGoogleSignInAsync()
    {
      var googleAuthenticationFile = await _envService.GetEnvironmentVariableValueAsync(_envOptions.Value.GoogleAuthentication);
      if (googleAuthenticationFile == null)
        throw new Exception("Could not find the actual google authentication file.");

      var googleAuthentication = JsonConvert.DeserializeObject<OAuth2Credentials>(googleAuthenticationFile);
      var redirectUri = googleAuthentication.RedirectUris.FirstOrDefault();
      var properties = new AuthenticationProperties
      {
        RedirectUri = Url.Action("GoogleResponseAsync")
      };
      return Challenge(properties, GoogleDefaults.AuthenticationScheme);
    }

    [HttpGet("response")]
    public async Task<ActionResult> GoogleResponseAsync()
    {
      Console.WriteLine("in response");
      var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
      if (!result.Succeeded)
        return Unauthorized();
      Debug.WriteLine(JsonConvert.SerializeObject(result));
      var userLinkDto = new UserLinkDto();
      var claims = result.Principal.Identities.FirstOrDefault().Claims.Select(claim => new
      {
        claim.Issuer,
        claim.OriginalIssuer,
        claim.Type,
        claim.Value,
      });
      claims.ForAll(claim =>
      {
        var claimType = Constants.GoogleClaimsDict.GetValueOrDefault(claim.Type);
        var dtoProp = claimType != null ? userLinkDto.GetType().GetProperty(claimType) : null;
        if (dtoProp != null)
          dtoProp.SetValue(userLinkDto, claim.Value);
      });
      return Ok();
    }

c# asp.net oauth-2.0 google-oauth
1个回答
0
投票

错误 400:redirect_uri_mismatch(这是正确的,因为我的应用程序没有 https://localhost:4200/signin-google)。

redirect_uri_mismatch 并不意味着您的应用程序没有

https://localhost:4200/signin-google
,它意味着您尚未在 Google 开发者控制台中为您的应用程序配置该重定向 uri 作为有效的重定向 uri。

如何修复redirect_uri_mismatch错误。

© www.soinside.com 2019 - 2024. All rights reserved.