クライアントアプリからのWEBサイトへのログイン認証方法について。
メモメモ
ベーシック認証
ブラウザでアクセスすると、IDとPASSの入力を促すダイアログが
表示されるタイプのサイトへのログイン。
クッキー認証(?)
mixiとかニコニコ動画とか、フォームにメアドとパスワードを入力して
ログインするタイプのサイトへのログイン。
ベーシック認証
ブラウザでアクセスすると、IDとパスワードの入力を促すダイアログが
表示されるタイプのサイトへのログイン方法です。
以下、WebCliantのDownloadDataメソッドによりサイトのHTMLをダウンロードするサンプルです。
Credentialsプロパティに認証情報を設定するだけでOKです。
using System;
using System.IO;
using System.Net;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
WebClient myweb = new WebClient();
//認証情報
myweb.Credentials = new NetworkCredential("ユーザーID", "パスワード");
//ダウンロード
byte[] pagedata = myweb.DownloadData("http://hoge.com/認証が必要なサイトのURL/");
//Encoding ec = Encoding.UTF8;
//取得先のサイトに合わせた文字コード設定
//Encoding ec = Encoding.UTF8;//UTF8の例
Encoding ec = Encoding.GetEncoding("shift-jis");//シフトGISの例
Console.WriteLine(ec.GetString(pagedata));
}
}
クッキー認証(ニコニコ動画へのログインサンプル)
mixiやニコニコ動画等、フォームにメアドとパスワードを入力してログインするタイプのサイトへのログインです。
ログイン時にクッキーを取得し、以降そのサイトへのアクセスには取得したクッキーを用いて認証します。
今回はニコニコ動画へログインする方法を記載します。
・ログインに必要な情報の調査
事前にログインフォームを解析し、ログインに必要な情報を調査します。
以下はニコニコ動画ログインページのHTMLを
ありがたい。
<form action="https://secure.nicovideo.jp/secure/login?site=niconico" method="post" onsubmit="if (tooAdvancedClock) alert(お使いの PC の時計が進みすぎているため、正常にログインができない場合がございます。);"> <input type="hidden" name="next_url" value=""> <dl> <dt><label for="mail">ログインメールアドレス</label></dt> <dd><input id="mail" name="mail" type="text" class="txt"></dd> <dt><label for="password">パスワード</label></dt> <dd> <input id="password" name="password" type="password" class="txt"> <p class="forgetPass">※パスワードを忘れた方は<a href="https://secure.nicovideo.jp/secure/remind_pass">再発行の手続き</a>へ</p> </dd> <dd class="buttons"> <div class="wrongPass"></div> <input type="submit" value="" class="submit"> </dd> </dl> </form>
・ログイン時アクセスすべきURLはhttps://secure.nicovideo.jp/secure/login?site=niconico
・必要なパラメタは、next_url、mail、passwordの3つ
・next_urlは空文字列””でよい
ログインパラメタ作成
//ニコニコ動画ログイン用IDとPASSWORDを指定
string id = "hoge@hoge.ne.jp";//メアド
string password = "hogehoge";//パスワード
//ログイン・ページへのアクセスパラメタ
//ここで必要な情報は、ログインページのHTMLソースを見て、
//"input"で検索して調べる
Hashtable vals = new Hashtable();
vals["next_url"] = "";
vals["mail"] = id;
vals["password"] = password;
//ログインボタンが押されたときにpostされるURL
//これもログインページのHTMLを見て、formタグから調べる
string url = "https://secure.nicovideo.jp/secure/login?site=niconico";
//パラメタを"param1=value1¶m2=value2"の形にまとめる
string param = "";
foreach (string k in vals.Keys)
{
param += String.Format("{0}={1}&", k, vals[k]);
}
byte[] data = Encoding.ASCII.GetBytes(param);
・POSTリクエスト発行
作成したパラメタを用いてPOSTリクエストを発行します。
//HTTP POSTリクエストの作成
CookieContainer cc = new CookieContainer(); //認証用クッキーを格納するコンテナ
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
req.CookieContainer = cc;
//POSTを実行
Stream reqStream = req.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
・GETリクエストによるクッキー取得
GETリクエストにより、クッキー及び認証後サイトのHTMLソースが取得できます。
//HTTP GETによるクッキーの取得
//GET実行
WebResponse res = req.GetResponse();
Stream resStream = res.GetResponseStream();
Encoding encoder = Encoding.GetEncoding("UTF-8");
StreamReader sr = new StreamReader(resStream, encoder);
string result = sr.ReadToEnd();
sr.Close();
resStream.Close();
Console.WriteLine(result);//ログイン後のHTMLが取得されている
・以降のアクセス
以降は取得したクッキーを使用したGETリクエストによりアクセスできます。
//以降はHTTP GETのみでアクセスできる
//例として、ニコニコ動画のマイページにアクセスしてみる
url = "http://www.nicovideo.jp/my/top";
//HTTP GET リクエストの作成
req = (HttpWebRequest)WebRequest.Create(url);
req.CookieContainer = cc;//取得済みのクッキーコンテナ
res = req.GetResponse();
resStream = res.GetResponseStream();
sr = new StreamReader(resStream, encoder);
result = sr.ReadToEnd();
sr.Close();
resStream.Close();
Console.WriteLine(result);//マイページのHTMLが取得されている
・ニコニコ動画ログインアプリのサンプル
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
public class Program
{
static void Main()
{
//ニコニコ動画ログイン用IDとPASSWORDを指定
string id = "hoge@hoge.ne.jp";//メアド
string password = "hogehoge";//パスワード
//ログイン・ページへのアクセスパラメタ
//ここで必要な情報は、ログインページのHTMLソースを見て、
//"input"で検索して調べる
Hashtable vals = new Hashtable();
vals["next_url"] = "";
vals["mail"] = id;
vals["password"] = password;
//ログインボタンが押されたときにpostされるURL
//これもログインページのHTMLを見て、formタグから調べる
string url = "https://secure.nicovideo.jp/secure/login?site=niconico";
//パラメタを"param1=value1¶m2=value2"の形にまとめる
string param = "";
foreach (string k in vals.Keys)
{
param += String.Format("{0}={1}&", k, vals[k]);
}
byte[] data = Encoding.ASCII.GetBytes(param);
//HTTP POSTリクエストの作成
CookieContainer cc = new CookieContainer(); //認証用クッキーを格納するコンテナ
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
req.CookieContainer = cc;
//POSTを実行
Stream reqStream = req.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
//HTTP GETによるクッキーの取得
//GET実行
WebResponse res = req.GetResponse();
Stream resStream = res.GetResponseStream();
Encoding encoder = Encoding.GetEncoding("UTF-8");
StreamReader sr = new StreamReader(resStream, encoder);
string result = sr.ReadToEnd();
sr.Close();
resStream.Close();
Console.WriteLine(result);//ログイン後のHTMLが取得されている
//以降はHTTP GETのみでアクセスできる
//例として、ニコニコ動画のマイページにアクセスしてみる
url = "http://www.nicovideo.jp/my/top";
//HTTP GET リクエストの作成
req = (HttpWebRequest)WebRequest.Create(url);
req.CookieContainer = cc;//取得済みのクッキーコンテナ
res = req.GetResponse();
resStream = res.GetResponseStream();
sr = new StreamReader(resStream, encoder);
result = sr.ReadToEnd();
sr.Close();
resStream.Close();
Console.WriteLine(result);//マイページのHTMLが取得されている
}
}
}
参考:http://www.atmarkit.co.jp/fdotnet/dotnettips/326cookie/cookie.html
これを参考に作ってみようかな、メモメモ