首页 > 解决方案 > 如何解决 ASP.NET MVC 中的 redirect_uri_mismatch?

问题描述

我创建了 ASP.NET MVC Web 应用程序以与谷歌日历 API 集成。

我已按照 Google 网站中的文档进行操作。我在 Google Developer 控制台中设置了如下项目:

在此处输入图像描述

创建项目后,我还下载了凭据文件,但是在使用它时,我uri_mismatch每次都会出错。

在此处输入图像描述

如何解决?

我的授权代码是:

string jsonFile = HttpContext.Server.MapPath("~/credentials.json");

            UserCredential credential;

            using (var stream =
                new FileStream(jsonFile, FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                //string credPath = "token.json";
                string credPath = HttpContext.Server.MapPath("~/token");
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

            // Define parameters of request.
            EventsResource.ListRequest request = service.Events.List("primary");
            request.TimeMin = DateTime.Now;
            request.ShowDeleted = false;
            request.SingleEvents = true;
            request.MaxResults = 10;
            request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

标签: c#asp.net-mvcgoogle-oauthgoogle-calendar-apigoogle-api-dotnet-client

解决方案


您在 Google Developer 控制台中设置的重定向 uri 必须与您发送的位置和期望返回的响应完全匹配。

我将假设您正在使用 Google .net 客户端库,因为您的回复说 /authorize 是在库中配置的

uri_mismatch 的解决方案

在谷歌开发者控制台中添加

http://localhost:63972/authorize

或者

http://127.0.0.1:63972/authorize

但请确保您在 IDE(visual studio)中设置了静态端口,否则您将再次遇到同样的问题。

提示 Web 应用程序与已安装的应用程序

您发布的代码使用GoogleWebAuthorizationBroker.AuthorizeAsync专为与已安装应用程序一起使用而设计的代码。当授权窗口打开时,它将在运行代码的机器上打开。当您在开发中时,它将在您的开发机器上打开,但是当您尝试将其发布到服务器时,它不会工作。

您应该使用GoogleAuthorizationCodeFlow以下示例Web 应用程序 (ASP.NET MVC)

using System;
using System.Web.Mvc;

using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Mvc;
using Google.Apis.Drive.v2;
using Google.Apis.Util.Store;

namespace Google.Apis.Sample.MVC4
{
    public class AppFlowMetadata : FlowMetadata
    {
        private static readonly IAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                {
                    ClientSecrets = new ClientSecrets
                    {
                        ClientId = "PUT_CLIENT_ID_HERE",
                        ClientSecret = "PUT_CLIENT_SECRET_HERE"
                    },
                    Scopes = new[] { DriveService.Scope.Drive },
                    DataStore = new FileDataStore("Drive.Api.Auth.Store")
                });

        public override string GetUserId(Controller controller)
        {
            // In this sample we use the session to store the user identifiers.
            // That's not the best practice, because you should have a logic to identify
            // a user. You might want to use "OpenID Connect".
            // You can read more about the protocol in the following link:
            // https://developers.google.com/accounts/docs/OAuth2Login.
            var user = controller.Session["user"];
            if (user == null)
            {
                user = Guid.NewGuid();
                controller.Session["user"] = user;
            }
            return user.ToString();

        }

        public override IAuthorizationCodeFlow Flow
        {
            get { return flow; }
        }
    }
}

推荐阅读