首页 > 解决方案 > 无需用户交互即可登录 Google 服务

问题描述

我正在尝试创建要在我不直接处理的云服务器(AppHarbor)中运行的应用程序服务,作为 C# 控制台应用程序。基本上,它是一个需要访问 Gmail 和 Google 日历的Telegram Bot 。在本地运行时,它会通过浏览器提示用户第一次访问该帐户。

不幸的是,在服务器中我无法授予该访问权限,因此我需要一种无需授权即可直接登录(身份验证)的方法。

我已经看到了使用Service Account的选项,但遗憾的是它需要GSuite来配置用户权限,并且我需要避免付款。

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

我已经生成了包含所有需要的设置和机密的 json 文件,但它仍然需要用户交互。

有没有办法在没有用户提示的情况下这样做?

标签: c#google-apigoogle-oauthgoogle-api-dotnet-clientappharbor

解决方案


USER

The term user denotes the owner of the data or the account you wish to access. In order to access data owned by a user account. You must have permission of the user in question.

Service Account

Service accounts are only indented for user when you the developer have access to the accounts in question. You are correct that you can only use them with gmail if the emails are controlled though a gsuite other wise there is no way to preauthorize them. service accounts

Oauth2 refresh token

I have done something like this in the past. What you are going to need is two applications. One which your users can run to authenticate your application and send the credentials to your server and the second is the console application you have now. Oauth

User Application

The user application should either be a web application or an installed application that the users can run. They run this application grant your application access (remember to add the offline scope) You will get a refresh token back. Take this refresh token and send it to the server that is running your console application.

Console application

your console application should then use these refresh tokens to request a new access token and gain access to the users data when ever it needs to.

To load this refresh token you will need to create your own implementation of IDataStore. The code you are using now usees FileDataStore which stores the crednetials in %appdata% you will need to over ride that so that it can read from where ever it is you had the user application store the data. I have a few examples here datastore.cs gist

Application verification

remember that you will need to have your application verified by google before you can release it GMAIL is one of the harder scopes to have approved you may want to start that process early.


推荐阅读