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

时间:2016-10-28 00:14:06

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

从根本上说,我对OAuth,Google和Google Apis一无所知。我在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日历。但是,我不能一直回到访问/刷新令牌(老实说,此时我并不确定我明白这些是什么)。我使用此代码从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;
    }

这是我知道如何取回当前访问/刷新令牌的唯一方法。我错过了什么有时它们存在,有时则不存在。 .Net Core 1.0版本的文档最多也很薄弱。有关通过Asp.Net核心访问Google Apis的更好方法的任何帮助吗?

1 个答案:

答案 0 :(得分:1)

由于您已设置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;
}