Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何设置GoogleWebAuthorizationBroker.AuthorizationAsync的返回uri?_C#_Asp.net_Oauth 2.0_Google Calendar Api - Fatal编程技术网

C# 如何设置GoogleWebAuthorizationBroker.AuthorizationAsync的返回uri?

C# 如何设置GoogleWebAuthorizationBroker.AuthorizationAsync的返回uri?,c#,asp.net,oauth-2.0,google-calendar-api,C#,Asp.net,Oauth 2.0,Google Calendar Api,我正在尝试在我的非MVC.NET Web应用程序中使用。(这似乎是一个重要的区别。) 我试着使用谷歌和Daimto的代码,以及一些网站的一些有用提示 我编写了以下方法: public void GetUserCredential( String userName ) { String clientId = ConfigurationManager.AppSettings[ "Google.ClientId" ]; //From Google Developer co

我正在尝试在我的非MVC.NET Web应用程序中使用。(这似乎是一个重要的区别。)

我试着使用谷歌和Daimto的代码,以及一些网站的一些有用提示

我编写了以下方法:

public void GetUserCredential( String userName )
{
    String clientId = ConfigurationManager.AppSettings[ "Google.ClientId" ];            //From Google Developer console https://console.developers.google.com
    String clientSecret = ConfigurationManager.AppSettings[ "Google.ClientSecret" ];    //From Google Developer console https://console.developers.google.com
    String[] scopes = new string[] {
            Google.Apis.Calendar.v3.CalendarService.Scope.Calendar          
    };

    // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
    UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync( new ClientSecrets
    {
        ClientId = clientId,
        ClientSecret = clientSecret             
    }, scopes, userName, CancellationToken.None, new FileDataStore( "c:\\temp" ) ).Result;

    // TODO: Replace FileDataStore with DatabaseDataStore
}
问题是,当调用Google的OAuth2页面时,
redirect\uURI
会一直设置为
http://localhost:/authorize
。我不知道如何将其设置为其他值,如下面由
AuthorizeAsync
生成的示例URL:

https://accounts.google.com/o/oauth2/auth?access_type=offline
    &response_type=code
    &client_id=********.apps.googleusercontent.com
    &redirect_uri=http:%2F%2Flocalhost:40839%2Fauthorize%2F
    &scope=https:%2F%2Fwww.googleapis.com%2Fauth%2Fcalendar
谷歌以一个重定向\u uri\u不匹配错误页面回应,并显示以下消息:

“请求中的重定向URI:与注册的重定向URI不匹配”

我只能在我的Google开发者控制台凭据页面中注册这么多重定向URI。我不想注册65535个端口,我想在我的网站上使用
/authorize
以外的页面。具体来说,我想在开发过程中使用
http://localhost:888/Pages/GoogleApiRedirect
,但除了在开发人员控制台中所做的工作之外,我不知道我将在哪里设置它

如何显式设置重定向uri的值?我也愿意接受“这种做法完全错误”的回应

编辑:

在过去的一天里玩过这个之后,我发现,通过对本机应用程序而不是Web应用程序使用客户端ID/客户端机密,我至少可以访问Google的Web授权页面,而不必抱怨重定向uri不匹配。这仍然是不可接受的,因为它仍然返回到
http://localhost:/authorize
,它不在我的web应用程序的控制范围内。

您可以使用此代码:(来自的原始想法)

dsAuthorizationBroker.cs

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Requests;
using Google.Apis.Util.Store;

namespace OAuth2
{    
    public class dsAuthorizationBroker : GoogleWebAuthorizationBroker
    {
        public static string RedirectUri;

        public new static async Task<UserCredential> AuthorizeAsync(
            ClientSecrets clientSecrets,
            IEnumerable<string> scopes,
            string user,
            CancellationToken taskCancellationToken,
            IDataStore dataStore = null)
        {
            var initializer = new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = clientSecrets,
            };
            return await AuthorizeAsyncCore(initializer, scopes, user,
                taskCancellationToken, dataStore).ConfigureAwait(false);
        }

        private static async Task<UserCredential> AuthorizeAsyncCore(
            GoogleAuthorizationCodeFlow.Initializer initializer,
            IEnumerable<string> scopes,
            string user,
            CancellationToken taskCancellationToken,
            IDataStore dataStore)
        {
            initializer.Scopes = scopes;
            initializer.DataStore = dataStore ?? new FileDataStore(Folder);
            var flow = new dsAuthorizationCodeFlow(initializer);
            return await new AuthorizationCodeInstalledApp(flow, 
                new LocalServerCodeReceiver())
                .AuthorizeAsync(user, taskCancellationToken).ConfigureAwait(false);
        }
    }


    public class dsAuthorizationCodeFlow : GoogleAuthorizationCodeFlow
    {
        public dsAuthorizationCodeFlow(Initializer initializer)
            : base(initializer) { }

        public override AuthorizationCodeRequestUrl
                       CreateAuthorizationCodeRequest(string redirectUri)
        {
            return base.CreateAuthorizationCodeRequest(dsAuthorizationBroker.RedirectUri);
        }
    }    
}
使用系统;
使用System.Collections.Generic;
使用系统线程;
使用System.Threading.Tasks;
使用Google.api.Auth.OAuth2;
使用Google.api.Auth.OAuth2.Flows;
使用Google.api.Auth.OAuth2.Requests;
使用Google.api.Util.Store;
名称空间OAuth2
{    
公共类dsAuthorizationBroker:GoogleWebAuthorizationBroker
{
公共静态字符串重定向URI;
公共新静态异步任务AuthorizeAsync(
客户机密客户机密,
IEnumerable作用域,
字符串用户,
CancellationToken任务CancellationToken,
IDataStore数据存储=空)
{
var initializer=新的GoogleAuthorizationCodeFlow.initializer
{
ClientSecrets=ClientSecrets,
};
return wait authorized asyncCore(初始值设定项、作用域、用户、,
taskCancellationToken,数据存储)。配置等待(false);
}
专用静态异步任务授权AsyncCore(
GoogleAuthorizationCodeFlow.初始值设定项初始值设定项,
IEnumerable作用域,
字符串用户,
CancellationToken任务CancellationToken,
IDataStore数据存储)
{
initializer.Scopes=范围;
initializer.DataStore=数据存储??新文件数据存储(文件夹);
var flow=新dsAuthorizationCodeFlow(初始值设定项);
返回等待新授权代码InstalledApp(流程,
新的LocalServerCodeReceiver())
.AuthorizeAsync(用户,taskCancellationToken).ConfigureAwait(false);
}
}
公共类dsAuthorizationCodeFlow:GoogleAuthorizationCodeFlow
{
公共dsAuthorizationCodeFlow(初始值设定项)
:base(初始值设定项){}
公共覆盖授权CodeRequestURL
CreateAuthorizationCodeRequest(字符串重定向URI)
{
返回base.CreateAuthorizationCodeRequest(dsAuthorizationBroker.RedirectUri);
}
}    
}

如果您试图在.NET应用程序非web服务器应用程序(即C#控制台应用程序命令行程序)中使用GoogleWebAuthorizationBroker.AuthorizationAsync,则在凭据中创建Google OAuth配置文件()时,选择以下内容至关重要。它是隐藏的,如果你不这样做,如果你选择单选按钮“其他”,它必须通过审批流程。另请注意,仅复制在以下步骤中创建的JSON参数的内容并用web应用程序版本替换您的客户端id/secret仍然会失败。为您的Google API控制台创建一个新的OAuth客户端概要文件

单击“帮助我选择”

选择您想要的API库ie(谷歌日历API) 选择“用户数据”

“是-无需授权文件”即Javascript和重定向 现在您有一个未经授权的个人资料

使用“下载JSON”并将其保存到应用程序中,以便在下面的代码中引用。当您查看这个文件时,您会注意到一组不同的参数,告诉代理这是一个应用程序。在本例中,我正在访问范围日历API。只需将作用域更改为您试图访问的任何API。

   string[] Scopes = { CalendarService.Scope.Calendar }; //requires full scope to get ACL list..
                string ApplicationName = "Name Of Your Application In Authorization Screen";

                //just reference the namespaces in your using block

                using (var stream = new FileStream("other_client_id.json", 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 = "other_token.json";
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        "user",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;               
                }

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

                //Then your ready to grab data from here using the methods mentioned in Google Calendar API docs
在创建oAuth客户端ID时选择“其他”有助于我解决重定向问题。(使用“Web应用程序”选项试图重定向到具有随机端口的某个url,这非常烦人)


现在我的Gmail API工作起来很有魅力:)

您是否尝试过将visual studio配置为在web应用程序项目中使用预定义的端口?检查此文档,以便您可以定义端口并在开发人员控制台中使用它。谢谢你的建议,杰拉尔多。是的,它已经为888端口进行了预配置。我还尝试了1024以上的“非特权”端口。我在一些类似于我的情况下看到过这个建议。如果它真的起作用,我想我可以接受
/authorize   string[] Scopes = { CalendarService.Scope.Calendar }; //requires full scope to get ACL list..
                string ApplicationName = "Name Of Your Application In Authorization Screen";

                //just reference the namespaces in your using block

                using (var stream = new FileStream("other_client_id.json", 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 = "other_token.json";
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        "user",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)).Result;               
                }

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

                //Then your ready to grab data from here using the methods mentioned in Google Calendar API docs