Youtube Data Api v3 : Authenticate User

Points To Remember


  1. You must have a project created in Developers console to use Youtube data api and other api's.
  2. You should save the youtube refresh token in a database or file where you can save it for a long time and use it.
  3. Youtube refresh token is generated only once, so if you want to regenerate it go to google accounts page and revoke access to your project and then re authenticate.
  4. To revoke access, go to Connected Apps and Sites in the above mentioned url and click on your project and then click revoke access to revoke access to the app.

Steps to Use Youtube Data Api v3

  1. You need to create a new Project in your at Developers Console.
  2. After creating a project you need to go to Project -> Api & auth -> Credentials , and then create a new Client ID.
  3. Go to Project -> Api & auth ->APIs and enable Youtube Analytics API and YouTube Data API v3. This will enable your project to use consume these api's.
  4. For using these api's in your application you need to setup the callback url. Go to Project -> Api & auth ->API -> Credentials
  5. You are all ready to use the youtube data api.
 In this tutorial we will see how to use the youtube data api in Grails. See how to use Youtube data api in Java example.

Add Rest Plugin to your project

BuildConfig.groovy
Add the following dependency to your project BuildConfig to enable rest calls using HttpBuilder.
compile ":rest:0.8"


Config.groovy
Save your data in the Config and use it in database, config used in this example is given below.
youtube{

    clientId="your_client_id"
    clientSecret="your_client_secret"
    scope ="https://gdata.youtube.com"
    responseType ="code"
    accessType="offline"
    redirectUrl = "http://localhost:8085/youtube/callBack"

    url{
        auth =  "https://accounts.google.com/o/oauth2/auth"
        token = "https://accounts.google.com/o/oauth2/token"
        userInfo = "https://www.googleapis.com/oauth2/v2/userinfo"
        dataApi = "https://www.googleapis.com/youtube/v3"
    }

}

Use Youtube Data Api v3

YoutubeController.groovy
Use this controller to authenticate the user from the google account and use youtube api. You should implement the logic to save the response data i.e. refresh token in database.
class YoutubeController {


    YoutubeAuthService youtubeAuthService


    def auth(){
        response.sendRedirect(youtubeAuthService.createAuthorizeRequest());
    }

    def callBack(String code){
        // User did not rejected authorization of your project
        if(!code)
            redirect(action: 'Error Action') 
        def object = youtubeAuthService.getAccessToken(code)

        // Save your Youtube Tokens to DB
        // or hit data api to get User info using access token and then save
        
        // chain the request to your success handler.
        chain(controller: 'controller', action: 'action')
    }
}

YoutubeAuthService.groovy
Use this service to get the access token and refresh tokens
package com.ekiras.youtube

import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method

import static groovyx.net.http.ContentType.URLENC

class YoutubeAuthService {

    def grailsApplication


    String createAuthorizeRequest() {
        String clientId = grailsApplication.config.youtube.clientId;
        String authUrl = grailsApplication.config.youtube.url.auth;
        String redirectUrl = grailsApplication.config.youtube.redirectUrl;
        String scope = grailsApplication.config.youtube.scope;
        String responseType = grailsApplication.config.youtube.responseType;
        String accessType = grailsApplication.config.youtube.accessType;

        String authRequest = authUrl + "?client_id=" + clientId + "&redirect_uri=" + redirectUrl + "&scope=" + scope + "&response_type=" + responseType +  "&access_type=" + accessType
        return authRequest;
    }

    def getAccessToken(String code){

        String clientId = grailsApplication.config.youtube.clientId;
        String clientSecret = grailsApplication.config.youtube.clientSecret;
        String tokenRequestUrl = grailsApplication.config.youtube.url.token;
        String redirectUrl = grailsApplication.config.youtube.redirectUrl;
        String grantType = "authorization_code";

        Map data = ['client_id':clientId,'client_secret':clientSecret,'code':code ,'redirect_uri':redirectUrl,'grant_type':grantType]
        HTTPBuilder httpBuilder = new HTTPBuilder(tokenRequestUrl);

        httpBuilder.request(Method.POST){
            requestContentType = URLENC
            body = data;
            response.success = {resp, reader ->
                // reader contains a access_token,token_type and expires_in
                return reader 
            }
            response.failure = {response, reader ->
                return null
            }
        }
    }

}

No comments:

Powered by Blogger.