How can I use ASP.NET MVC Owin AccessToken in Google.Apis call?

北慕城南 提交于 2019-12-05 08:33:38
Douglas Gandini

Linda helped me with an URL pointing to a new asp.net mvc sample (https://codereview.appspot.com/194980043/).

I just had to add AccessType = "offline" to GoogleOAuth2AuthenticationOptions and save some extra info to create a new instance of TokenResponse when I need.

Google Authentication Options

private GoogleOAuth2AuthenticationOptions ConfigureGooglePlus()
{

    var goolePlusOptions = new GoogleOAuth2AuthenticationOptions()
    {
        AccessType = "offline",
        ClientId = "Xxxxxxx.apps.googleusercontent.com",
        ClientSecret = "Yyyyyyyyyy",
        Provider = new GoogleOAuth2AuthenticationProvider()
        {
            OnAuthenticated = context =>
            {
                context.Identity.AddClaim(new System.Security.Claims.Claim("Google_AccessToken", context.AccessToken));

                if (context.RefreshToken != null)
                {
                    context.Identity.AddClaim(new Claim("GoogleRefreshToken", context.RefreshToken));
                }
                context.Identity.AddClaim(new Claim("GoogleUserId", context.Id));
                context.Identity.AddClaim(new Claim("GoogleTokenIssuedAt", DateTime.Now.ToBinary().ToString()));
                var expiresInSec = (long)(context.ExpiresIn.Value.TotalSeconds);
                context.Identity.AddClaim(new Claim("GoogleTokenExpiresIn", expiresInSec.ToString()));


                return Task.FromResult(0);
            }
        },

        SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
    };

    goolePlusOptions.Scope.Add("https://www.googleapis.com/auth/plus.login");
    goolePlusOptions.Scope.Add("https://www.googleapis.com/auth/plus.me");
    goolePlusOptions.Scope.Add("https://www.googleapis.com/auth/userinfo.email");

    return goolePlusOptions;
}

How to retrieve the credentials (using token info "stored" as claim)

private async Task<UserCredential> GetCredentialForApiAsync()
{
    var initializer = new GoogleAuthorizationCodeFlow.Initializer
    {
        ClientSecrets = new ClientSecrets
        {
            ClientId = "Xxxxxxxxx.apps.googleusercontent.com",
            ClientSecret = "YYyyyyyyyyy",
        },
        Scopes = new[] { 
        "https://www.googleapis.com/auth/plus.login", 
        "https://www.googleapis.com/auth/plus.me", 
        "https://www.googleapis.com/auth/userinfo.email" }
    };
    var flow = new GoogleAuthorizationCodeFlow(initializer);

    var identity = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ApplicationCookie);

    var userId = identity.FindFirstValue("GoogleUserId");

    var token = new TokenResponse()
    {
        AccessToken = identity.FindFirstValue("Google_AccessToken"),
        RefreshToken = identity.FindFirstValue("GoogleRefreshToken"),
        Issued = DateTime.FromBinary(long.Parse(identity.FindFirstValue("GoogleTokenIssuedAt"))),
        ExpiresInSeconds = long.Parse(identity.FindFirstValue("GoogleTokenExpiresIn")),
    };

    return new UserCredential(flow, userId, token);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!