Oauth 2.0 如何在ASP.NET网站中创建和集成Google Apps Marketplace?

Oauth 2.0 如何在ASP.NET网站中创建和集成Google Apps Marketplace?,oauth-2.0,openid,google-apps-marketplace,Oauth 2.0,Openid,Google Apps Marketplace,我有一个网站,我想在Google Apps Marketplace上创建一个应用程序。并希望将此应用程序集成到我的网站。google用户使用google帐户登录,只需单击应用程序并重定向到我的网站,所有身份验证都使用google最新的身份验证api预处理。请帮助整合 谢谢。我们发现从头开始编写代码是最容易的。您将需要创建一个网页,所有谷歌应用程序用户将首先重定向到该网页 我已经在下面加入了我们代码的缩短版本: Imports System Imports System.Data Imports

我有一个网站,我想在Google Apps Marketplace上创建一个应用程序。并希望将此应用程序集成到我的网站。google用户使用google帐户登录,只需单击应用程序并重定向到我的网站,所有身份验证都使用google最新的身份验证api预处理。请帮助整合


谢谢。

我们发现从头开始编写代码是最容易的。您将需要创建一个网页,所有谷歌应用程序用户将首先重定向到该网页

我已经在下面加入了我们代码的缩短版本:

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
导入系统
导入系统数据
导入System.Data.SqlClient
导入System.IO
导入系统.Net
导入Newtonsoft.Json
部分类google_oauth2
继承System.Web.UI.Page
Dim client_id As String=“xxx您的客户id在此xxx”
Dim client_secret As String=“xxx您的客户机密在此xxx”
受保护的子页加载(ByVal sender作为对象,ByVal e作为System.EventArgs)处理Me.Load
Dim代码为String=Request.QueryString(“代码”)
如果code=”“,则
步骤1()
其他的
步骤2(代码)
如果结束
端接头
第1分步()
Dim作用域为String=“”
范围+=”https://www.googleapis.com/auth/userinfo.profile"
范围+=”+https://www.googleapis.com/auth/userinfo.email"
范围+=”+https://www.googleapis.com/auth/calendar"
范围+=”+https://www.google.com/m8/feeds/"
'#
Dim step1_URL=”https://accounts.google.com/o/oauth2/auth?"
步骤1_URL+=“scope=“+scope
步骤1\u URL+=“&状态=%2Fprofile”
步骤1\u URL+=“&redirect\u uri=https%3A%2F%2Fwww.example.com%2Fauth%2Fgoogle\u oauth2%2FDefault.aspx”
步骤1\u URL+=“&response\u type=code”
步骤1_URL+=“&client_id=“+client_id
步骤1\u URL+=“&批准\u提示=自动”
步骤1\u URL+=“&access\u type=联机”
'step1_URL+=“&access_type=offline”'添加此项以使其返回刷新令牌
响应.重定向(步骤1\u URL)
端接头
子步骤2(代码为字符串)
'当从步骤1收到“代码”时,将其发布到Google以获取代币
Dim step2_URL=”https://accounts.google.com/o/oauth2/token"
Dim access_令牌作为字符串=“”
Dim refresh_标记为字符串=“”
Dim post_数据为字符串=“”
Dim response_json As String=“”
尝试
post_数据+=“代码=”+代码
post_数据+=”&客户端_id=“+客户端_id”
post_data+=“&client_secret=“+client_secret”
post_data+=“&redirect_uri=https%3A%2F%2Fwww.example.com%2Fauth%2Fgoogle_oauth2%2FDefault.aspx”
post_数据+=“&grant_类型=授权码”
post_data+=“&包含已授予的_作用域=True”
response_json=PostData(步骤2_URL,post_数据)
Label_message.Text=response_json
'#
Dim a作为GoogleAuthData=JsonConvert.DeserializeObject(GoogleAuthData的)(响应_json)
访问令牌=a.access\u令牌
刷新令牌=a.refresh\u令牌
Label_message.Text+=“
访问令牌:”+access\u令牌 特例 Label_message.Text+=“
步骤2错误:”+ex.message 结束尝试 '########################## “如果有必要,在这里做些事情 “试试看 'Dim get_url作为字符串='https://www.googleapis.com/calendar/v3/users/me/calendarList" 'response\u json=sendGetRequest(获取url、访问令牌) 'Label_message.Text+=“


GET
”+response\u json “特例 “Label_message.Text+=”



获取错误
“+ex.message “结束尝试 '########################## '获取用户ID和域 如果访问令牌“”,则 尝试 Dim get_url作为字符串=”https://www.googleapis.com/oauth2/v2/userinfo" response_json=sendGetRequest(获取url、访问令牌) Label_message.Text+=“


GET
”+response_json Dim u As GoogleUserData=JsonConvert.DeserializeObject(属于GoogleUserData)(响应_json) Dim user_id作为字符串=u.id Dim user_域作为字符串=u.hd Dim user_email As String=u.email Dim给定名称为字符串=u。给定名称 Dim family_name作为字符串=u.family_name Label_message.Text+=“

用户ID:”+User_ID Label_message.Text+=“

域:”+user_域 会话(“google_oauth2_id”)=用户id 会话(“google_oauth2_域”)=用户_域 会话(“谷歌oauth2电子邮件”)=用户电子邮件 会话(“google_oauth2_给定名称”)=给定名称 Session(“google_oauth2_family_name”)=family_name 会话(“google\u oauth2\u访问\u令牌”)=访问\u令牌 会话(“google\u oauth2\u刷新\u令牌”)=刷新\u令牌 '在此处添加代码以将用户数据保存到数据库 '将用户转发到系统中 Response.Redirect(“/Default.aspx”) 特例 Label_message.Text+=“



获取错误
”+ex.message 结束尝试 其他的 Label_message.Text+=“
无AccessToken” 如果结束 端接头 子RefreshAccessToken(将令牌刷新为字符串) '使用此选项可从刷新令牌获取新的访问令牌 调暗此URL=”https://accounts.google.com/o/oauth2/token" Dim post_数据为字符串=“” post_数据+=“客户机_机密=“+客户机_机密” post_数据+=“&授予_类型=刷新\u令牌” post_数据+=”&刷新_令牌=“+刷新_令牌” post_数据+=”&客户端_id=“+客户端_id” Dim response_json As String=PostData(这个URL,PostData) Label_message.Text=response_json '# 像粘液一样暗淡