如何在用户访问我的网站时将用户登录到谷歌?

时间:2015-02-03 20:33:38

标签: google-api-dotnet-client

我正在开发解决方案的标志,并且需要能够在用户访问网站时将用户登录到他们的Google帐户,以便他们可以访问任何Google服务。我正在从谷歌访问并刷新令牌并将其保存到我的数据库,但我不知道如何使用这些令牌来记录用户。

        public async Task<ActionResult> IndexAsync(CancellationToken cancellationToken)
    {
        flowData = new AppFlowMetadata();
        UsersSSOTokens userToken = GetCurrentUserToken();

        if (userToken != null)
        {
            CheckTokenValid(userToken);
            LogIntoGoogleWithToken();
        }
        else
            if (result == null || result.Credential == null)
            {
                result = await new AuthorizationCodeMvcApp(this, flowData).
                    AuthorizeAsync(cancellationToken);

                if (result.Credential == null) return new RedirectResult(result.RedirectUri);
            }

        return View();
    }

        public async Task<ActionResult> GetResult(string code, string error, string state)
    {
        var returnUrl = Request.Url.ToString();
        returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?"));
        var userId = Session["user"];

        var token = await flowData.Flow.ExchangeCodeForTokenAsync(userId.ToString(), code, returnUrl,
            CancellationToken.None);

        if (token != null && error == null)
        {
            if (token.AccessToken != null && token.RefreshToken != null)
                SaveToken(token.AccessToken, token.RefreshToken, token.TokenType, token.Issued, token.Scope);
        }

        return new RedirectResult(state);
    }

1 个答案:

答案 0 :(得分:0)

当您拥有访问/刷新令牌时,用户将有效登录。注销/登录主要是客户端概念。在服务器端,在您的应用程序被授权代表用户进行API调用之后,您应该做的就是进行这些API调用,例如。

TokenResponse token = new TokenResponse
{
    AccessToken = this.GoogleAccessToken,
    RefreshToken = this.GoogleRefreshToken
};

IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
    new GoogleAuthorizationCodeFlow.Initializer
    {
        ClientSecrets = PlusHelper.GetClientConfiguration().Secrets,
        Scopes = new string[] { PlusService.Scope.PlusLogin }
    });

UserCredential credential = new UserCredential(flow, "me", token);
bool success = credential.RefreshTokenAsync(CancellationToken.None).Result;

PlusService plusService = new PlusService(
    new Google.Apis.Services.BaseClientService.Initializer()
    {
        ApplicationName = "Haikunamata",
        HttpClientInitializer = credential
    });

Person me = await plusService.People.Get(@"me").ExecuteAsync();