using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Configuration;
using System.Text;
using System.Web;
using System.Net;
using System.IO; namespace Twitter
{
class Auth {
const string REQUEST_TOKEN_URL = "https://twitter.com/oauth/request_token";
const string ACCESS_TOKEN_URL = "https://twitter.com/oauth/access_token";
const string AUTHORIZE_URL = "https://twitter.com/oauth/authorize"; private Random random = new Random(); public string ConsumerKey { get; private set; }
public string ConsumerSecret { get; private set; }
public string RequestToken { get; private set; }
public string RequestTokenSecret { get; private set; }
public string AccessToken { get; private set; }
public string AccessTokenSecret { get; private set; }
public string UserId { get; private set; }
public string ScreenName { get; private set; } public Auth(string consumerKey, string consumerSecret) {
ServicePointManager.Expect100Continue = false;
ConsumerKey = consumerKey;
ConsumerSecret = consumerSecret;
} public Auth(string consumerKey, string consumerSecret, string accessToken, string accessTokenSecret, string userId, string screenName) {
ServicePointManager.Expect100Continue = false;
ConsumerKey = consumerKey;
ConsumerSecret = consumerSecret;
AccessToken = accessToken;
AccessTokenSecret = accessTokenSecret;
UserId = userId;
ScreenName = screenName;
} public void GetRequestToken() {
SortedDictionary<string, string> parameters = GenerateParameters("");
string signature = GenerateSignature("", "GET", REQUEST_TOKEN_URL, parameters);
parameters.Add("oauth_signature", UrlEncode(signature));
string response = HttpGet(REQUEST_TOKEN_URL, parameters);
Dictionary<string, string> dic = ParseResponse(response);
RequestToken = dic["oauth_token"];
RequestTokenSecret = dic["oauth_token_secret"];
} public string GetAuthorizeUrl() {
return AUTHORIZE_URL + "?oauth_token=" + RequestToken;
} public void GetAccessToken(string pin) {
SortedDictionary<string, string> parameters = GenerateParameters(RequestToken);
parameters.Add("oauth_verifier", pin);
string signature = GenerateSignature(RequestTokenSecret, "GET", ACCESS_TOKEN_URL, parameters);
parameters.Add("oauth_signature", UrlEncode(signature));
string response = HttpGet(ACCESS_TOKEN_URL, parameters);
Dictionary<string, string> dic = ParseResponse(response);
AccessToken = dic["oauth_token"];
AccessTokenSecret = dic["oauth_token_secret"];
UserId = dic["user_id"];
ScreenName = dic["screen_name"];
} public string Get(string url, IDictionary<string, string> parameters) {
SortedDictionary<string, string> parameters2 = GenerateParameters(AccessToken);
foreach (var p in parameters)
parameters2.Add(p.Key, p.Value);
string signature = GenerateSignature(AccessTokenSecret, "GET", url, parameters2);
parameters2.Add("oauth_signature", UrlEncode(signature));
return HttpGet(url, parameters2);
} public string Post(string url, IDictionary<string, string> parameters) {
SortedDictionary<string, string> parameters2 = GenerateParameters(AccessToken);
foreach (var p in parameters)
parameters2.Add(p.Key, p.Value);
string signature = GenerateSignature(AccessTokenSecret, "POST", url, parameters2);
parameters2.Add("oauth_signature", UrlEncode(signature));
return HttpPost(url, parameters2);
} private string HttpGet(string url, IDictionary<string, string> parameters) {
WebRequest req = WebRequest.Create(url + '?' + JoinParameters(parameters));
WebResponse res = req.GetResponse();
Stream stream = res.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
reader.Close();
stream.Close();
return result;
} string HttpPost(string url, IDictionary<string, string> parameters) {
byte[] data = Encoding.ASCII.GetBytes(JoinParameters(parameters));
WebRequest req = WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
Stream reqStream = req.GetRequestStream();
reqStream.Write(data, 0, data.Length);
reqStream.Close();
WebResponse res = req.GetResponse();
Stream resStream = res.GetResponseStream();
StreamReader reader = new StreamReader(resStream, Encoding.UTF8);
string result = reader.ReadToEnd();
reader.Close();
resStream.Close();
return result; } private Dictionary<string, string> ParseResponse(string response) {
Dictionary<string, string> result = new Dictionary<string, string>();
foreach (string s in response.Split('&')) {
int index = s.IndexOf('=');
if (index == -1)
result.Add(s, "");
else
result.Add(s.Substring(0, index), s.Substring(index + 1));
}
return result;
} private string JoinParameters(IDictionary<string, string> parameters) {
StringBuilder result = new StringBuilder();
bool first = true;
foreach (var parameter in parameters) {
if (first)
first = false;
else
result.Append('&');
result.Append(parameter.Key);
result.Append('=');
result.Append(parameter.Value);
}
return result.ToString();
} private string GenerateSignature(string tokenSecret, string httpMethod, string url, SortedDictionary<string, string> parameters) {
string signatureBase = GenerateSignatureBase(httpMethod, url, parameters);
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = Encoding.ASCII.GetBytes(UrlEncode(ConsumerSecret) + '&' + UrlEncode(tokenSecret));
byte[] data = System.Text.Encoding.ASCII.GetBytes(signatureBase);
byte[] hash = hmacsha1.ComputeHash(data);
return Convert.ToBase64String(hash);
} private string GenerateSignatureBase(string httpMethod, string url, SortedDictionary<string, string> parameters) {
StringBuilder result = new StringBuilder();
result.Append(httpMethod);
result.Append('&');
result.Append(UrlEncode(url));
result.Append('&');
result.Append(UrlEncode(JoinParameters(parameters)));
return result.ToString();
} private SortedDictionary<string, string> GenerateParameters(string token) {
SortedDictionary<string, string> result = new SortedDictionary<string, string>();
result.Add("oauth_consumer_key", ConsumerKey);
result.Add("oauth_signature_method", "HMAC-SHA1");
result.Add("oauth_timestamp", GenerateTimestamp());
result.Add("oauth_nonce", GenerateNonce());
result.Add("oauth_version", "1.0");
if (!string.IsNullOrEmpty(token))
result.Add("oauth_token", token);
return result;
} public string UrlEncode(string value) {
string unreserved = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
StringBuilder result = new StringBuilder();
byte[] data = Encoding.UTF8.GetBytes(value);
foreach (byte b in data) {
if (b < 0x80 && unreserved.IndexOf((char)b) != -1)
result.Append((char)b);
else
result.Append('%' + String.Format("{0:X2}", (int)b));
}
return result.ToString();
} private string GenerateNonce() {
string letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
StringBuilder result = new StringBuilder(8);
for (int i = 0; i < 8; ++i)
result.Append(letters[random.Next(letters.Length)]);
return result.ToString();
} private string GenerateTimestamp() {
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
} class Program {
const string CONSUMER_KEY = "hogehogehogehogehoge";
const string CONSUMER_SECRET = "fugafugafugafugafugafugafugafuga"; static void Main(string[] args)
{
Auth auth;
var settings = Twitter.Properties.Settings.Default; if (string.IsNullOrEmpty((string)settings["AccessToken"])) {
auth = new Auth(CONSUMER_KEY, CONSUMER_SECRET); // リクエストトークンを取得する
auth.GetRequestToken(); // ユーザーにRequestTokenを認証してもらう
Console.WriteLine("次のURLにアクセスして暗証番号を取得してください:");
Console.WriteLine(auth.GetAuthorizeUrl());
Console.Write("暗証番号:");
string pin = Console.ReadLine().Trim(); // アクセストークンを取得する
auth.GetAccessToken(pin); // 結果を表示する
Console.WriteLine("AccessToken: " + auth.AccessToken);
Console.WriteLine("AccessTokenSecret: " + auth.AccessTokenSecret);
Console.WriteLine("UserId: " + auth.UserId);
Console.WriteLine("ScreenName: " + auth.ScreenName); // アクセストークンを設定ファイルに保存する
settings["AccessToken"] = auth.AccessToken;
settings["AccessTokenSecret"] = auth.AccessTokenSecret;
settings["UserId"] = auth.UserId;
settings["ScreenName"] = auth.ScreenName;
settings.Save();
} else {
// 設定ファイルから読み込む
auth = new Auth(CONSUMER_KEY, CONSUMER_SECRET,
(string)settings["AccessToken"], (string)settings["AccessTokenSecret"],
(string)settings["UserId"], (string)settings["ScreenName"]);
} // ↓ここらへんは後でちゃんとwrapしたい // タイムラインから3件取得してみる
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("count", "3");
Console.WriteLine(auth.Get("http://twitter.com/statuses/home_timeline.xml", parameters)); // ポストしてみる
Console.WriteLine("いまどうしてる?");
string status = Console.ReadLine();
parameters.Clear();
parameters.Add("status", auth.UrlEncode(status));
Console.WriteLine(auth.Post("http://twitter.com/statuses/update.xml", parameters));
}
}
}

oauth2认证的更多相关文章

  1. 基于Node的PetShop,oauth2认证RESTful API

    前篇 - 基本认证,用户名密码 后篇 - OAuth2 认证 前文使用包passport实现了一个简单的用户名.密码认证.本文改用oauth2来实现更加安全的认证.全部代码在这里. OAUTH2 用户 ...

  2. 新浪微博的OAuth2认证过程

    1. 创建应用 在weibo.com上申请一个应用,获取app key和app secret, 填写redirect uri 2. 获取code 通过在浏览器访问 https://api.weibo. ...

  3. 使用Fiddler获取OAuth2认证的access token时候返回502

    微软动态CRM专家罗勇 ,回复322或者20190402可方便获取本文,同时可以在第一间得到我发布的最新博文信息,follow me! 我这里Fiddler的Composer功能来获取OAuth2 认 ...

  4. Spring Cloud下基于OAUTH2认证授权的实现

    GitHub(spring -boot 2.0.0):https://github.com/bigben0123/uaa-zuul 示例(spring -boot 2.0.0): https://gi ...

  5. OAuth2认证和授权:AuthorizationCode认证

    前面的OAuth2认证,里面的授权服务器都是用的identityserver4搭建的 ids4没有之前一般都是Owin搭建授权服务器,博客园有很多 ids4出来后,一般都是用ids4来做认证和授权了, ...

  6. OAuth2认证有一定的了解

    转到分享界面后,进行OAuth2认证: 以新浪为例: 第一步.WebView加载界面,传递参数 使用WebView加载登陆网页,通过Get方法传递三个参数:应用的appkey.回调地址和展示方式dis ...

  7. asp.net 、C#实现微信企业号OAuth2认证

    以微信企业号作为入口的应用,几乎都会遇到需要应用系统中个人信息和微信用户关联问题.从而进行其他业务处理.目前所做项目采取在企业号通讯录添加自定义字段存入应用系统用户信息表中唯一标识UserGuid进行 ...

  8. 怎样用Google APIs和Google的应用系统进行集成(4)----获得Access Token以通过一些Google APIs的OAuth2认证

    在上篇文章中: "怎样用Google APIs和Google的应用系统进行集成(3)----调用发现Google APIs的RESTful的服务"一文中,我们直接用jdk的java ...

  9. Oauth2认证模式之授权码模式实现

    Oauth2认证模式之授权码模式(authorization code) 本示例实现了Oauth2之授权码模式,授权码模式(authorization code)是功能最完整.流程最严密的授权模式.它 ...

  10. 【Servlet】基于Jsp的微信Oauth2认证

    作者:yongh701 挂载到微信服务器上的应用程序,能够通过微信Oauth2认证,能够抓取到用户的微信信息,当然,你首先要通过微信的帐号资质审核. 一.基本思想 二.基本过程 1.登陆微信的公众平台 ...

随机推荐

  1. 推荐使用Tiny Framework web开发UI组件

    TINY FRAMEWORK 基于组件化的J2EE开发框架,from:http://www.tinygroup.org/   名字 Tiny名称的来历 取名Tiny是取其微不足道,微小之意. Tiny ...

  2. poj 1458 Common Subsequence_最长公共子串

    题意:略 求最长公共子串 #include<iostream> #include<cstdio> #include<string> using namespace ...

  3. Longest Substring Without Repeating Characters 最长不重复子串

    只遍历一次字符串即可求出最长不重复子串的长度. int lengthOfLongestSubstring(string s) { vector<,-); //记录字符上一次出现的位置,ASCII ...

  4. 如何使用TestFlight进行App构建版本测试(转)

    在日常的开发当中,当一个项目在开发过程中或者完成准备上线,都需要我们进行真机测试,否则不可能开发完了就直接扔到了App,等上线了再下载看看,这都是不可能的.那么说到真机测试,大家肯定会想到弄一个99美 ...

  5. jquery获取父窗口的元素[转]

    $("#父窗口元素ID",window.parent.document); 对应javascript版本为window.parent.document.getElementById ...

  6. SQL_SERVER日期函数详细用法

    1.一个月第一天的 Select DATEADD(mm, DATEDIFF(mm,0,getdate()), 0) 2.本周的星期一 Select DATEADD(wk, DATEDIFF(wk,0, ...

  7. grep 和 sed:linux经常使用工具 &amp; 基本正則表達式

    grep 见链接:http://www.cyberciti.biz/faq/grep-regular-expressions/ sed參考文章:http://www.thegeekstuff.com ...

  8. Android的Bitmap和BitmapDrawable类解析-android学习之旅(六十)

    使用简单图片 使用Drawable对象 bitmap和BitmapDrawable对象 package peng.liu.test; import android.app.Activity; impo ...

  9. JavaScript中模块“写法”

    在JavaScript模块到底是什么 event = function() { // do more return { bind: function() {}, unbind: function() ...

  10. mysql jdbc 查询连接问题

    做了一个测试,mysql jdbc 链接A调用setAutoCommit,设置false,查询指定数据,可以查询出来,另个一链接把指定的数据给删除了,第一个链接在此查询的时候,仍然可以查询出来,使用的 ...