You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC 5调用Google My Business API获取评论遇认证问题求助

问题解决方案

一、先解决重定向URI不匹配问题

Google OAuth控制台配置的重定向URI必须和程序实际回调地址完全一致:

  • ASP.NET MVC 5 + Owin的Google认证默认回调路径是/signin-google,所以你需要在Google Cloud Console的OAuth 2.0客户端ID设置中添加完整URI:
    • 开发环境:https://localhost:xxxx/signin-google(替换xxxx为你的项目端口)
    • 生产环境:https://你的域名.com/signin-google
  • 注意区分HTTP/HTTPS,本地调试启用HTTPS的话必须填HTTPS地址。

二、修复identity为空的问题

核心错误修正

你调用GetExternalIdentityAsync时用了DefaultAuthenticationTypes.ApplicationCookie,这是本地登录的Cookie类型,外部登录的身份信息存在DefaultAuthenticationTypes.ExternalCookie中,修改代码:

var identity = await HttpContext.GetOwinContext().Authentication.GetExternalIdentityAsync(
    DefaultAuthenticationTypes.ExternalCookie); 

补充登录流程检查

确保你已经正确触发Google外部登录流程,比如在Account控制器中实现以下基础动作:

[AllowAnonymous]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
    var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
    var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
    HttpContext.GetOwinContext().Authentication.Challenge(properties, provider);
    return new HttpUnauthorizedResult();
}

[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
    var loginInfo = await HttpContext.GetOwinContext().Authentication.GetExternalLoginInfoAsync();
    if (loginInfo == null)
    {
        return RedirectToAction("Login");
    }
    // 将外部身份转换为本地应用身份并登录
    var identity = new ClaimsIdentity(loginInfo.ExternalIdentity.Claims, DefaultAuthenticationTypes.ApplicationCookie);
    HttpContext.GetOwinContext().Authentication.SignIn(identity);
    return RedirectToLocal(returnUrl);
}

额外优化点

  1. 明确回调路径:在Startup.Auth.cs中显式配置回调路径,避免默认路径冲突:
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
    ClientId = "xxxMyClientID",
    ClientSecret = "xxxMyclientsecret",
    CallbackPath = new PathString("/signin-google") // 和控制台配置的URI保持一致
});
  1. 正确获取用户ID:Google返回的用户ID对应Claim类型是ClaimTypes.NameIdentifier,无需自定义MyClaimTypes:
var userId = identity.FindFirstValue(ClaimTypes.NameIdentifier);
  1. 添加API权限范围:如果要调用Google API(如获取企业评论),需要在认证配置中声明所需Scope:
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
    ClientId = "xxxMyClientID",
    ClientSecret = "xxxMyclientsecret",
    Scope = new[] { "https://www.googleapis.com/auth/your-target-api-scope" }, // 替换为实际所需API权限
    CallbackPath = new PathString("/signin-google")
});

内容的提问来源于stack exchange,提问作者M.S.WebFustion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 06:27:49