现在有些网站有了Google账户登录的功能,如下图,这样的登录方式其实对用户是有益的。只要我有个google账号,就能登录有利用Google这个登录服务的网站。此功能详解请参考
此功能的流程图:
描述:
以www.sopif.com为例
http://www.sopif.com/logintest.aspx这个页面,里面有个按钮,按钮对应的事件代码
Code
string s = "https://www.google.com/accounts/AuthSubRequest?next=http%3A%2F%2Fwww.sopif.com%2Flhking.aspx&scope=http%3A%2F%2Fwww.google.com%2Fcalendar%2Ffeeds%2F&session=1&secure=1";
Response.Redirect(s);
next参数,就是google登录成功后,重定向的页面,scope就是你要访问的google服务。
我的next参数页面时lhking.aspx
页面代码:
Code
object token;
protected void Page_Load(object sender, EventArgs e)
{
token = Request.QueryString["token"];
if (token != null)
{
Response.Write("你用Google账户登录成功!"+"<br />");
Response.Write(token.ToString());
}
else
{
Response.Write("你用Google账户登录失败!");
}
}
这样就行了。大家可以测试,这种情况下,google只会返回一个token,用户名和密码都是安全的。
要想获得google返回来的邮箱地址和姓名:
请参看一下类,用的时候,直接 Response.Redirect(new GoogleLogin().getLoginUrl()); //Google账户登录
Code
/// <summary>
/// 提供google账户的登录
/// </summary>
public class GoogleLogin : ILoginService
{
string urlAuthSubRequest = "https://www.google.com/accounts/AuthSubRequest?";
string next = ILoginService.WebsiteUrl() + "/Auth/Handle.aspx";
string scope = "http://www.google.com/m8/feeds/contacts/default/thin?max-results=0";
string urldata = "";
/// <summary>
/// 生成登录用的url
/// </summary>
/// <returns></returns>
public override string getLoginUrl()
{
return urlAuthSubRequest + "next=" + HttpUtility.UrlEncode(next) + "&scope=" + HttpUtility.UrlEncode(scope);
}
/// <summary>
/// 得到Google账户的Email地址和姓名
/// </summary>
/// <param name="page"></param>
/// <returns></returns>
public override string[] parseHandle(HttpContext page)
{
urldata = scope;
string[] ret = new string[2];
try
{
string token = page.Request["token"];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(urldata));
request.Headers.Add("Authorization", "AuthSub token=" + token);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
XmlDocument doc = new XmlDocument();
if (response != null)
{
string account = string.Empty, name = string.Empty;
doc.Load(response.GetResponseStream());
XmlNode node = doc.SelectSingleNode("*/*[local-name()='id']");
if (node != null)
{
account = node.InnerText; //Email地址
}
node = doc.SelectSingleNode("*/*[local-name()='author']/*[local-name()='name']");
if (node != null)
{
name = node.InnerText; //姓名
}
ret[0] = account;
ret[1] = name;
return ret;
}
else return ret;
}
catch (Exception ex)
{
new MyException("GoogleLogin", ex.ToString());
return new string[] { "", "" };
}
}
}