检索 Google Api 的访问和刷新令牌

Retrieving Access and Refresh Token for Google Api

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

        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,
        });

很简单。然后我想使用 Google 日历。但是,我无法始终如一地取回 Access/Refresh 令牌(老实说,此时我不确定我是否理解这些是什么)。我使用此代码从 google:

取回日历服务
    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;
    }

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

因为你已经设置了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;
}