c# - 检索 Google Api 的访问和刷新 token

标签 c# google-api asp.net-core google-calendar-api google-oauth

从根本上说,我对 OAuth、Google 和 Google Apis 并不了解。我正在使用 Asp.Net Core 1.0 中的 v3 库。我使用谷歌身份验证:

        app.UseGoogleAuthentication(new GoogleOptions
        {
            ClientId = Configuration["Google:ClientId"],
            ClientSecret = Configuration["Google:ClientSecret"],
            Scope = {
            "email",
            "https://www.googleapis.com/auth/userinfo.email",
            "profile",
            "https://www.googleapis.com/auth/userinfo.profile",
            "openid",
            "https://www.googleapis.com/auth/calendar",
        },
            AccessType = "offline",
            SaveTokens = true,
        });

很简单。然后我想使用谷歌日历。但是,我无法始终如一地取回访问/刷新 token (老实说,此时我不确定我是否理解它们是什么)。我使用此代码从谷歌取回日历服务:

    private AuthorizationCodeFlow CreateFlow(IEnumerable<string> scopes)
    {
        return new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
        {
            ClientSecrets = new Google.Apis.Auth.OAuth2.ClientSecrets
            {
                ClientId = _ClientId,
                ClientSecret = _ClientSecret
            },
            DataStore = new MemoryDataStore(),
            Scopes = scopes
        });
    }

    private async Task<UserCredential> CreateUserCredential(HttpContext context, string providerKey, IEnumerable<string> scopes)
    {
        var flow = CreateFlow(scopes);
        var token = await context.GetGoogleTokenResponse();

        UserCredential credential = new UserCredential(flow, providerKey, token);
        return credential;
    }

    public async Task<CalendarService> CreateCalendarServiceAsync(HttpContext context, string providerKey)
    {
        if (string.IsNullOrWhiteSpace(providerKey)) return null;
        if (context == null) return null;

        var credential = await CreateUserCredential(context, providerKey, new[] { "https://www.googleapis.com/auth/calendar" });
        CalendarService service = new CalendarService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential,
            ApplicationName = _ApplicationName,
        });

        return service;
    }

    public static async Task<TokenResponse> GetGoogleTokenResponse(this HttpContext context)
    {
        var info = await context.Authentication.GetAuthenticateInfoAsync("Google");
        if (info == null) return null;

        var token = new TokenResponse
        {
            AccessToken = info.Properties.Items[".Token.access_token"],
            RefreshToken = info.Properties.Items[".Token.refresh_token"],
            TokenType = info.Properties.Items[".Token.token_type"],
            Issued = DateTime.Parse(info.Properties.Items[".issued"]),
        };

        return token;
    }

这是我知道如何取回当前访问/刷新 token 的唯一方法。我错过了什么。有时它们存在,有时不存在。 .Net Core 1.0 版本的文档充其量只是简陋的。关于通过 Asp.Net Core 访问 Google Apis 的更好方法有什么帮助吗?

最佳答案

因为您已经设置了 SaveTokens = true,您可以像这样获取 access_token:await context.Authentication.GetTokenAsync("access_token");

所以像下面这样改变你的方法可能会解决你的问题:

private async Task<UserCredential> CreateUserCredential(HttpContext context, string providerKey, IEnumerable<string> scopes)
{
    var flow = CreateFlow(scopes);
    var token = await context.Authentication.GetTokenAsync("access_token");

    UserCredential credential = new UserCredential(flow, providerKey, token);
    return credential;
}

关于c# - 检索 Google Api 的访问和刷新 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40296106/

相关文章:

c# - google calendar api - 请求太多用户

asp.net - 使用asp.net core身份将数据存储在cookie中

c# - nservicebus + webhooks +Errors +MaxRetries

c# - 无法加载文件或程序集。即使它位于正确的位置并且构建良好

c# - Executenonquery InvalidOperationException

android - 谷歌图书 API

ruby-on-rails - 客户端未经授权使用此方法检索访问 token

asp.net-core - .NET Core Web 应用程序项目中缺少默认的 "appsettings.json"文件

c# - 如何在 ASP.Net Core 中注入(inject) WCF 服务客户端?

c# - 长路径\\?\解决方法不适用于某些安装