1050422_ASP.NET 實作GOOGLE 驗證(使用ASPSnippets.GoogleAPI)

ASPSnippets.GoogleAPI 下載位址(含範例說明)

http://www.aspsnippets.com/Articles/Login-with-Google-Account-API-in-ASPNet-and-get-Google-Plus-Profile-details.aspx

這個網址的元件比較舊,驗證時會常常出現要求離線存取的權限。

 

http://www.aspsnippets.com/DownloadFile.aspx?File=ASPSnippets.GoogleAPI.dll

這個版本比較新,不會常常要求離線存取的權限

 

這兒做個備份

https://drive.google.com/open?id=0B0W-2RaWohmDZ1p1d1FkblBaUjA

 

設定前要先在GOOGLE API CONSOLE 設定好要使用的 ClientID ClientSecret

請參考這篇

http://www1.dcps.tn.edu.tw/wp/sammy/?p=2014

 

把DLL檔放進 ASP.NET的BIN目錄內

程式片段如下(按下GOOGLE驗證按鈕)


protected
void btnGoogle_Click(object sender, EventArgs e)

{

//設定GOOGLE CLIENT ID


GoogleConnect.ClientId = MyVar.GoogleClientID;

 

//設定GOOGLE SECRET


GoogleConnect.ClientSecret = MyVar.GoogleClientSecret;

 

//設定驗證回傳位址為目前目錄內的googleCallBack.aspx


GoogleConnect.RedirectUri = “http://”+ Request.Url.Authority + Request.ApplicationPath + (Request.ApplicationPath ==“/”? “”:“/”)+“GoogleCallBack.aspx”;

 

//要求驗證


GoogleConnect.Authorize(“profile”, “email”);

}

 

 

回傳頁面GoogleCallBack.aspx 程式片斷如下

using ASPSnippets.GoogleAPI;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Script.Serialization;

using System.Web.UI;

using System.Web.UI.WebControls;

 

public
partial
class
GoogleCallBack : System.Web.UI.Page

{


protected
void Page_Load(object sender, EventArgs e)

{


if (Request.QueryString[“error”] == “access_denied” || string.IsNullOrEmpty(Request.QueryString[“code”]))

{


MyFunction.allert(“Google登入失敗”);

Response.Redirect(“default.aspx”);

}


string code = “”;


string json = “”;


try

{

code = Request.QueryString[“code”];

json = GoogleConnect.Fetch(“me”, code);

}


catch

{


MyFunction.allert(“Goolge驗證發生異常,請聯絡系統管理員檢查驗證相關設定。”);

Response.Redirect(“default.aspx”);

}


GoogleProfile profile = new
JavaScriptSerializer().Deserialize<GoogleProfile>(json);

 

取回電子郵件當ID

string googleid = profile.Emails.Find(email => email.Type == “account”).Value; ;

 

 

//取回姓名和電子郵件

u.username = profile.DisplayName;

u.email = profile.Emails.Find(email => email.Type == “account”).Value;

}

 


public
class
GoogleProfile

{


public
string Id { get; set; }


public
string DisplayName { get; set; }


public
Image Image { get; set; }


public
List<Email> Emails { get; set; }


public
string Gender { get; set; }


public
string ObjectType { get; set; }

}

 


public
class
Email

{


public
string Value { get; set; }


public
string Type { get; set; }

}

 


public
class
Image

{


public
string Url { get; set; }

}

}

跳至工具列