Search code examples
javascriptangulargoogle-apigmail-api

How to get authorization_code from Gmail API in angular 5 app


I am working in an Angular app, I want to add Gmail in this Angular app.

I have followed this tutorial https://medium.com/@mcflyDev/angular-2-or-4-import-google-contacts-d0ffb13d8626

everything is working fine and I am getting the success response with access_token but I am not getting authorization_code.

How can I get authorization_code?

Here is my configuration:

     this.auth2 = gapi.auth2.init({
        client_id: 'bla-bla-bla-2.apps.googleusercontent.com',
        cookiepolicy: 'single_host_origin',
        scope: 'https://www.googleapis.com/auth/gmail.readonly',
        access_type: 'offline',
        response_type: 'code',
        auth_uri: 'https://accounts.google.com/o/oauth2/v2/auth',
        prompt: 'select_account',
        include_granted_scopes: true,
        grant_type: 'authorization_code',
      });

Also, I am also not getting refresh_token, as you can see I have already set access_type: 'offline'.

enter image description here

I am getting this response as shown in the above image.

Thanks.


Solution

  • I got the solution. Earlier I was making a POST Ajax call but that was not required.

    We just need to do a small setup in 2 steps:

    Step 1. Prepare a URL:

    The URL should look like this:

     https://accounts.google.com/o/oauth2/auth?redirect_uri=:your_redirect_url&response_type=code&client_id=:your_client_id&scope=https://www.googleapis.com/auth/gmail.send&approval_prompt=force&access_type=offline
    

    You can paste this URL in your browser and hit enter to check it is working.

    Step 2. Create an anchor tag in HTML:

    <a href="giveAboveURLHere">Connect With Gmail</a>
    

    Congratulations!!! You have done.

    Whenever user will click on this link, Google will ask for permission for the provided scope and if the access is granted by the end user then Google will redirect to the given redirect_url with the authorization_code in the query param.

    Then on the server side, you will need to make another API call with this authorization_code then Google will provide access_token and refresh_token.

    Thanks, I hope it will help.