Question

I have a website and i want to create an app on Google Apps Marketplace. and want to integrate this app to my website. the google user logged in with google account just click the app and redirected to my website with all authentication pre processed with google's latest authentication api. Please help to integrate.

Thank you.

Was it helpful?

Solution

We found it easiest to write the code from scratch. You will need to create a single web page to which all Google Apps users are first redirected.

I've included a shortened version of our code below:

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Net
Imports Newtonsoft.Json


Partial Class google_oauth2
    Inherits System.Web.UI.Page

    Dim client_id As String = "xxx your client id here xxx"
    Dim client_secret As String = "xxx your client secret here xxx"


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim code As String = Request.QueryString("code")
        If code = "" Then
            step1()
        Else
            step2(code)
        End If
    End Sub

    Sub step1()
        Dim scope As String = ""
        scope += "https://www.googleapis.com/auth/userinfo.profile"
        scope += "+https://www.googleapis.com/auth/userinfo.email"
        scope += "+https://www.googleapis.com/auth/calendar"
        scope += "+https://www.google.com/m8/feeds/"
        '#
        Dim step1_URL = "https://accounts.google.com/o/oauth2/auth?"
        step1_URL += "scope=" + scope
        step1_URL += "&state=%2Fprofile"
        step1_URL += "&redirect_uri=https%3A%2F%2Fwww.example.com%2Fauth%2Fgoogle_oauth2%2FDefault.aspx"
        step1_URL += "&response_type=code"
        step1_URL += "&client_id=" + client_id
        step1_URL += "&approval_prompt=auto"
        step1_URL += "&access_type=online"
        'step1_URL += "&access_type=offline" 'add this to get it to return a refresh token
        Response.Redirect(step1_URL)
    End Sub

    Sub step2(code As String)
        'when the 'code' is received from step 1, post this to Google to get tokens
        Dim step2_URL = "https://accounts.google.com/o/oauth2/token"
        Dim access_token As String = ""
        Dim refresh_token As String = ""
        Dim post_data As String = ""
        Dim response_json As String = ""
        Try
            post_data += "code=" + code
            post_data += "&client_id=" + client_id
            post_data += "&client_secret=" + client_secret
            post_data += "&redirect_uri=https%3A%2F%2Fwww.example.com%2Fauth%2Fgoogle_oauth2%2FDefault.aspx"
            post_data += "&grant_type=authorization_code"
            post_data += "&include_granted_scopes = True"
            response_json = PostData(step2_URL, post_data)
            Label_message.Text = response_json
            '#
            Dim a As GoogleAuthData = JsonConvert.DeserializeObject(Of GoogleAuthData)(response_json)
            access_token = a.access_token
            refresh_token = a.refresh_token
            Label_message.Text += "<br/>access_token: " + access_token
        Catch ex As Exception
            Label_message.Text += "<br/>Step2 Error: " + ex.Message
        End Try


        '##########################
        'do stuff here if necessary
        'Try
        '    Dim get_url As String = "https://www.googleapis.com/calendar/v3/users/me/calendarList"
        '    response_json = sendGetRequest(get_url, access_token)
        '    Label_message.Text += "<br/><br/><br/>GET<br/>" + response_json
        'Catch ex As Exception
        '    Label_message.Text += "<br/><br/><br/>GET ERROR<br/>" + ex.Message
        'End Try


        '##########################
        'Get the user ID and domain
        If access_token <> "" Then
            Try
                Dim get_url As String = "https://www.googleapis.com/oauth2/v2/userinfo"
                response_json = sendGetRequest(get_url, access_token)
                Label_message.Text += "<br/><br/><br/>GET<br/>" + response_json
                Dim u As GoogleUserData = JsonConvert.DeserializeObject(Of GoogleUserData)(response_json)
                Dim user_id As String = u.id
                Dim user_domain As String = u.hd
                Dim user_email As String = u.email
                Dim given_name As String = u.given_name
                Dim family_name As String = u.family_name
                Label_message.Text += "<br/><br/>User ID: " + user_id
                Label_message.Text += "<br/><br/>Domain: " + user_domain
                Session("google_oauth2_id") = user_id
                Session("google_oauth2_domain") = user_domain
                Session("google_oauth2_email") = user_email
                Session("google_oauth2_given_name") = given_name
                Session("google_oauth2_family_name") = family_name
                Session("google_oauth2_access_token") = access_token
                Session("google_oauth2_refresh_token") = refresh_token
'add code here to save the user data to database
'forward user into system
Response.Redirect("/Default.aspx")
            Catch ex As Exception
                Label_message.Text += "<br/><br/><br/>GET ERROR<br/>" + ex.Message
            End Try
        Else
            Label_message.Text += "<br/>No AccessToken"
        End If

    End Sub

    Sub RefreshAccessToken(refresh_token As String)
        'use this to get a new access token from a refresh token
        Dim this_URL = "https://accounts.google.com/o/oauth2/token"

        Dim post_data As String = ""
        post_data += "client_secret=" + client_secret
        post_data += "&grant_type=refresh_token"
        post_data += "&refresh_token=" + refresh_token
        post_data += "&client_id=" + client_id

        Dim response_json As String = PostData(this_URL, post_data)
        Label_message.Text = response_json
        '#
        Dim a As GoogleAuthData = JsonConvert.DeserializeObject(Of GoogleAuthData)(response_json)
        Dim access_token As String = a.access_token
    End Sub

    Function PostData(request_url As String, post_data As String) As String
        Dim wReq As HttpWebRequest = WebRequest.Create(request_url)
        wReq.ContentType = "application/x-www-form-urlencoded"
        wReq.UserAgent = "Example"
        wReq.Timeout = 10 * 1000
        wReq.AllowAutoRedirect = False
        wReq.ContentLength = post_data.Length
        wReq.Method = "POST"

        'Try
        Dim sReq As StreamWriter = New StreamWriter(wReq.GetRequestStream())
        sReq.Write(post_data)
        sReq.Flush()
        sReq.Close()

        '###############################################
        Dim wResp As HttpWebResponse = wReq.GetResponse()
        Dim sResp As StreamReader = New StreamReader(wResp.GetResponseStream())
        Dim responseXML As String = sResp.ReadToEnd()
        sResp.Close()
        Return responseXML
    End Function


    Function sendGetRequest(ByVal URL As String, access_token As String) As String
        Dim responseXML As String = ""
        Dim request As WebRequest = WebRequest.Create(URL)
        request.Method = "GET"
        request.ContentType = "text/html"
        'System.Net.HttpRequestHeader.Authorization
        request.Headers.Add("Authorization", "Bearer " + access_token)
        Dim response As WebResponse = request.GetResponse()
        Dim dataStream As Stream = response.GetResponseStream()
        Dim reader As New StreamReader(dataStream)
        responseXML = reader.ReadToEnd()
        reader.Close()
        dataStream.Close()
        response.Close()
        '#
        Return responseXML
    End Function



    Sub saveTokens(ByVal google_access_token As String, ByVal google_refresh_token As String)
        'save the tokens to your database here for reuse
    End Sub

    Sub getTokens()
        'get the tokens from your database here
    End Sub


End Class

Public Class GoogleAuthData
    Public Property token_type As String = ""
    Public Property expires_in As String = ""
    Public Property id_token As String = ""
    Public Property access_token As String = ""
    Public Property refresh_token As String = ""
    Public Property [error] As String = ""
    Public Property error_description As String = ""
End Class

Public Class GoogleUserData
    Public Property id As String = "" 'unique id
    Public Property email As String = ""
    Public Property verified_email As String = ""
    Public Property name As String = ""
    Public Property given_name As String = ""
    Public Property family_name As String = ""
    Public Property link As String = ""
    Public Property picture As String = ""
    Public Property gender As String = ""
    Public Property locale As String = ""
    Public Property hd As String = "" 'domain
End Class
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top