もふぬこ動画☆画像

かわいい!おもしろい!猫動画と猫画像を毎日更新!(たまに違う記事も書いています)

ASP.NET(C#)でGoogleのOAuth2を使う方法

PHPでOAuth使おうと思っていたらASP.NET(C#)になったよ!

 

PHPの場合はこちらのサイトを参考に。さくっとできました。

Google OAuth + PHP でログイン処理の実装

http://temog.info/archives/programming/google-oauth-php.html

 

ASP.NETはこちらを参考にしました。

☆  [Google API] GoogleAPIのOAuth2を使ってみる

http://morado106.blog106.fc2.com/blog-entry-93.html

 

認証コード発行の部分とアクセストークンを取得した後の処理が無いのでその部分は自分で作る必要がありました。

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.Specialized;
using System.Web;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq; 

public static class GoogleOAuth
{
static string[] Scopes = new String[] {
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile" };

/// <summary>
    /// 認証用URL生成
    ///  このURLにRedirectするとGoogle認証開始
    /// </summary>

public static string GetAuthUrl(string indexPath, string clientID)
{
string baseUrl = "https://accounts.google.com/o/oauth2/auth?";
// 認証用URL生成
string authUrl = baseUrl + "scope=" + GetUrlEncode() + "&redirect_uri="
+ indexPath + "&response_type=code&client_id=" + clientID;
return authUrl;
}

/// <summary>
/// Google OAuth認証を使用してIDを取得する
/// </summary>
public static string GetEmailFromGoogle(string code, string indexPath, string clientID, string clientSecret)
{
// 送信するデータ
StringBuilder post = new StringBuilder();
post.AppendFormat("code={0}&", code);
post.AppendFormat("client_id={0}&", clientID);
post.AppendFormat("client_secret={0}&", clientSecret);
post.AppendFormat("redirect_uri={0}&", indexPath);
post.Append("grant_type=authorization_code");
byte[] postDataBytes = Encoding.UTF8.GetBytes(post.ToString());

// 送信先の設定
Uri uri = new Uri("https://accounts.google.com/o/oauth2/token");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postDataBytes.Length;
req.AllowAutoRedirect = false;

// リクエストの送信
System.IO.Stream reqStream = req.GetRequestStream();
reqStream.Write(postDataBytes, 0, postDataBytes.Length);
reqStream.Close();

// レスポンスの取得
System.Net.WebResponse res = req.GetResponse();
System.IO.Stream resStream = res.GetResponseStream();
System.IO.StreamReader sr = new System.IO.StreamReader(resStream, System.Text.Encoding.GetEncoding("UTF-8"));
string jsonStr = sr.ReadToEnd();
sr.Close();

// レスポンスからアクセストークンを取得
JObject jObject = JsonConvert.DeserializeObject(jsonStr) as JObject;
string accessToken = jObject["access_token"].ToString();

// アクセストークンを使いメールアドレスを取得
uri = new Uri("https://www.googleapis.com/oauth2/v2/userinfo?" + "access_token=" + accessToken);
req = (HttpWebRequest)WebRequest.Create(uri);

// レスポンスの取得
res = req.GetResponse();
resStream = res.GetResponseStream();
sr = new System.IO.StreamReader(resStream, System.Text.Encoding.GetEncoding("UTF-8"));
jsonStr = sr.ReadToEnd();
sr.Close();
jObject = JsonConvert.DeserializeObject(jsonStr) as JObject;
return jObject["email"].ToString();
}

/// <summay>
    /// 文字列配列のURLエンコードを実行し、&で結合した文字列を返す
/// </summay>
private static string GetUrlEncode()
{
string value = string.Empty;
foreach(string scope in Scopes)
{
if(value != string.Empty)
{
value += "&";
}
value += HttpUtility.UrlEncode(scope);
}
return value;
}
}
 


GetAuthUrlメソッドとメールアドレスを取得するところは作っていますがそれ以外はほぼパクリです(笑)

呼び出しはこんな感じで。 

[index.aspx]

        string indexPath = HttpUtility.UrlEncode("http://hogehoge.com/index.aspx");
        string clientID = "クライアントID";
	string clientSecret = "クライアントシークレット");
        if (Page.Request["code"] == null)
{ string url = GoogleOAuth.GetAuthUrl(indexPath, clientID); Response.Redirect(url); } else { string email = GoogleOAuth.GetEmailFromGoogle(Page.Request["code"], indexPath, clientID, clientSecret); } 

 Redirectした後、自分自信(index.aspx)に戻して返ってきたcodeを使ってGmailのアドレスを取得しています。

 ※少しブログ用に書き換えた部分があるのでタイプミスとかあるかもしれません。

 間違いがあったらご指摘ください。