Github的第三方驗證


Github的第三方驗證

隨着近年來網絡安全越來越受到重視,對於用戶認證和用戶信息保存模塊的開發也提升到了一個新的高度。
一般小型網站開發的時候,由於技術水平和時間成本有限,很有可能會開發出一些或大或小的問題。幸好有許多第三方的OAuth服務可能幫我們簡化這個問題。
由於http://codesnippet.info/ 是一個技術網站,所以一般使用本網站的用戶都會有Github賬號。
同時,通過獲取Github賬號的個人基本信息,對於用戶之間的交流(Github的電子郵件),用戶水平的了解(追隨者數量)也有很大幫助。

為你的網站申請APP第三方驗證

首先你必須要有一個Github的賬號。如何申請Github的賬號,這里就不需要再啰嗦了。
注意這里的ClientID和SecretCode是整個OAuth的憑證,不要將這個信息泄露出去。

  • Application Name:應用名稱(重要)
  • HomePageURL:網站的URL
  • ApplicationDescription:網站描述
  • Authorization callback URL:回調地址 (重要)

關於回調地址,我原來有個誤區,認為是Github服務器將數據Post到我的網站,就像微信公眾平台那樣,其實這里的回調地址是客戶的瀏覽器發出的重定向地址。同時,這個地址是可以使用 localhost 的,這樣的話對於我們調試程序會帶來巨大的好處。

第三方認證的開發

認證按鈕

string clientid = "https://github.com/login/oauth/authorize?client_id=" + ConfigurationManager.AppSettings["ClientID"];

整個認證的起始點是瀏覽器對於這個鏈接的訪問,這里需要你的ClientID信息,這個信息是對所有人公開的。
網站看上去是這個樣子的
https://github.com/login/oauth/authorize?client_id=01a8bf26baecfa8db577

認證后的回調

如果用戶通過了驗證,則瀏覽器將被重新定向到你定義的回調網址,同時會帶上一個code參數
你的程序需要將這個code參數,以及你的ClientID和SecretID來獲得AccessToken。
這里有幾個地方必須注意:
UserAgent必須有,而且是AppName!
這個方法不能用Winform程序調試,因為這樣可能造成一些跨域訪問的問題。雖然使用Winform可以獲得Code,但是AccessToken是無論如何也無法獲得的!
獲得了AccessToken之后,可以獲得用戶的信息了,不過這個AccessToken不是寫在獲得用戶信息的URL里面的,而是寫在HTTPHEAD里面的。

       /// <summary>
        /// 獲得login
        /// </summary>
        /// <param name="Code"></param>
        /// <returns></returns>
        public static GithubAccount GetUserInfo(string Code)
        {
            try
            {
                var resonseJson = "";
                var webRequest = WebRequest.Create(githubTokenUrl) as HttpWebRequest;
                webRequest.Method = "POST";
                webRequest.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
                //Github API V3必須加上下面這句話!
                webRequest.UserAgent = AppName;
                var postData = string.Format("code={0}&client_id={1}&client_secret={2}", Code, ClientID, ClientSecret);

                //在HTTP POST請求中傳遞參數
                using (var sw = new StreamWriter(webRequest.GetRequestStream()))
                {
                    sw.Write(postData);
                    sw.Close();
                }

                //發送請求,並獲取服務器響應
                using (var response = webRequest.GetResponse())
                {
                    using (var sr = new StreamReader(response.GetResponseStream()))
                    {
                        resonseJson = sr.ReadToEnd();
                    }
                }

                var resultparms = resonseJson.Split("&".ToCharArray());
                var accessToken = string.Empty;
                foreach (var parm in resultparms)
                {
                    if (parm.StartsWith("access_token="))
                    {
                        accessToken = parm.Split("=".ToCharArray())[1];
                    }
                }

                webRequest = WebRequest.Create("https://api.github.com/user") as HttpWebRequest;
                webRequest.Method = "GET";
                webRequest.Headers.Add("Authorization", "token " + accessToken);
                //Github API V3必須加上下面這句話!
                webRequest.UserAgent = AppName;

                using (var response = webRequest.GetResponse())
                {
                    using (var sr = new StreamReader(response.GetResponseStream()))
                    {
                        dynamic obj = JsonConvert.DeserializeObject(sr.ReadToEnd());
                        GithubAccount gitlogin = new GithubAccount()
                        {
                            Login = obj.login,
                            Avatar_url = obj.avatar_url,
                            Email = obj.email,
                            Name = obj.name,
                            Html_url = obj.html_url,
                            Company = obj.company,
                            Blog = obj.blog,
                            Location = obj.location,
                            Followers = obj.followers,
                            Following = obj.following,
                            LastAccess = DateTime.Now
                        };
 						//省略
                }
            }
            catch (Exception ex)
            {
                InfraStructure.Log.ExceptionLog.Log("SYSTEM", "GitHubOAuth", "GET USER INFO", ex.ToString());
                return null;
            }
        }

個人基本信息

從github賬號中可以獲得的個人基本信息如下:

{
  "login": "magicdict",
  "id": 897796,
  "avatar_url": "https://avatars.githubusercontent.com/u/897796?v=3",
  "gravatar_id": "",
  "url": "https://api.github.com/users/magicdict",
  "html_url": "https://github.com/magicdict",
  "followers_url": "https://api.github.com/users/magicdict/followers",
  "following_url": "https://api.github.com/users/magicdict/following{/other_user}",
  "gists_url": "https://api.github.com/users/magicdict/gists{/gist_id}",
  "starred_url": "https://api.github.com/users/magicdict/starred{/owner}{/repo}",
  "subscriptions_url": "https://api.github.com/users/magicdict/subscriptions",
  "organizations_url": "https://api.github.com/users/magicdict/orgs",
  "repos_url": "https://api.github.com/users/magicdict/repos",
  "events_url": "https://api.github.com/users/magicdict/events{/privacy}",
  "received_events_url": "https://api.github.com/users/magicdict/received_events",
  "type": "User",
  "site_admin": false,
  "name": "MagicHu",
  "company": "Shanghai Chuwa software co.ltd",
  "blog": "http://www.mywechatapp.com",
  "location": "Shanghai,China",
  "email": "mynightelfplayer@hotmail.com",
  "hireable": true,
  "bio": null,
  "public_repos": 7,
  "public_gists": 0,
  "followers": 50,
  "following": 2,
  "created_at": "2011-07-06T09:26:40Z",
  "updated_at": "2016-02-06T09:09:34Z"
}

參考資料

An introduction to the ASP.NET 5 Generic OAuth Provider


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM