alireza
alireza

Reputation: 31

google ExchangeCodeForTokenAsync invalid_grant in webapi

i have implemented GoogleAuthorizationCodeFlow scenario from google api client dotnet and tutorial to get token from what my client sent to server as a code. but when i call flow.ExchangeCodeForTokenAsync , I get the following error :

{"Error:\"invalid_grant\", Description:\"\", Uri:\"\""}

I read google authorization invalid_grant and gusclass oauth 2 using google dotnet api client libraries but they didn't help me and. I think it must be very simple but I don't know why it doesn't work. For client side , I have used Satellizer and this is my server Codes:

public bool PostExchangeAccessToken(GoogleClientAccessCode code)
        {
            string[] SCOPES = { "email" };
            IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = new ClientSecrets()
                {
                    ClientSecret = "******",
                    ClientId = "********.apps.googleusercontent.com"
                },
                Scopes = SCOPES
            });
            try
            {
                TokenResponse token;
                token = flow.ExchangeCodeForTokenAsync("*****@gmail.com", Newtonsoft.Json.JsonConvert.SerializeObject(code), "https://localhost:44301/",
                                CancellationToken.None).Result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return true;
        }

what is the problem?

Upvotes: 1

Views: 2554

Answers (2)

alireza
alireza

Reputation: 31

On Github I found that I must use the Token from the client and use

GoogleAuthorizationCodeFlow.Initializer() 

to create my UserCredential object.

Upvotes: 1

You can check your google developer console settings.(Authorized redirect URIs)

Credentials => OAuth 2.0 client IDs => Your Application Settings => Authorized redirect URIs

You must add url. ("https://localhost:44301/")

My code :

 flow.ExchangeCodeForTokenAsync("me", authCode, redirectUri, CancellationToken.None).Result;

Authorized redirect URIs

For use with requests from a web server. This is the path in your application that users are redirected to after they have authenticated with Google. The path will be appended with the authorization code for access. Must have a protocol. Cannot contain URL fragments or relative paths. Cannot be a public IP address.

Upvotes: 0

Related Questions