0

I am developing a singe sign on solution and need to be able to log a user into their Google account whenever they use visit the site so they can access any Google services. I am getting access and refresh token from google and saving them to my database but I don't know what to do with these tokens to log the user in.

        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 Answers1

0

When you have the access/refresh tokens, the user is effectively logged in. Sign out / Sign in are mostly a client-side notion. On the server-side, all you should be doing after your app has been authorized to make API calls on behalf of the user is to make those API calls, e.g.

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();
class
  • 8,621
  • 29
  • 30