若是對OAuth2.0有任何的疑問,請先熟悉OAuth2.0基礎的文章:http://www.cnblogs.com/alunchen/p/6956016.htmlhtml
1. 前言git
本篇文章時對 客戶端的受權模式-受權碼模式 的建立,固然你理解的最複雜的模式以後,其餘模式都是在受權碼模式上面作一些小改動便可。對於受權碼模式有任何的疑問,請看上面提到的文章。github
注意:本文是建立OAuth的Server端,不是Client請求端。json
2. 開始受權碼模式的概念、流程小程序
第2點其實就是複製了上一篇文章,爲了提升閱讀性,讀過上一篇文章的可略過第2點。緩存
受權碼模式(authorization code)是功能最完整、流程最嚴密的受權模式。它的特色就是經過客戶端的後臺服務器,與"服務提供商"的認證服務器進行互動。安全
流程圖:服務器
圖說明:微信
(A)用戶訪問客戶端,後者將前者導向認證服務器。session
(B)用戶選擇是否給予客戶端受權。
(C)假設用戶給予受權,認證服務器將用戶導向客戶端事先指定的"重定向URI"(redirection URI),同時附上一個受權碼。
(D)客戶端收到受權碼,附上早先的"重定向URI",向認證服務器申請令牌。這一步是在客戶端的後臺的服務器上完成的,對用戶不可見。
(E)認證服務器覈對了受權碼和重定向URI,確認無誤後,向客戶端發送訪問令牌(access token)和更新令牌(refresh token)。
下面是上面這些步驟所須要的參數。
A步驟中,客戶端申請認證的URI,包含如下參數:
例子:
GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1 Host: server.example.com
C步驟中,服務器迴應客戶端的URI,包含如下參數:
例子:
HTTP/1.1 302 Found Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA &state=xyz
D步驟中,客戶端向認證服務器申請令牌的HTTP請求,包含如下參數:
例子:
POST /token HTTP/1.1 Host: server.example.com Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW Content-Type: application/x-www-form-urlencoded grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb
E步驟中,認證服務器發送的HTTP回覆,包含如下參數:
例子:
HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store Pragma: no-cache { "access_token":"2YotnFZFEjr1zCsicMWpAA", "token_type":"example", "expires_in":3600, "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA", "example_parameter":"example_value" }
從上面代碼能夠看到,相關參數使用JSON格式發送(Content-Type: application/json)。此外,HTTP頭信息中明確指定不得緩存。
3. 開始寫本身的OAuth2.0服務端代碼(C#)
若是有錯誤的地方,歡迎指正,做者也不保證徹底正確。
這裏介紹的是C#,固然你能夠用你本身的語言寫,大同小異。(沒用到第三方關於OAuth2.0的框架)
做者在開始理解OAuth2.0的概念時,化了一段比較長的時間。從微信受權開始接觸OAuth2.0的概念,後來寫了一套第三方微信受權的小程序,慢慢消化OAuth2.0。
說實在的,OAuth2.0安全在於,提供了code、access_token,來綁定咱們的用戶信息。而且code、access_token有過時的時間。因此,關鍵在於理解code與access_token的做用。
開始代碼,咱們建立一個MVC的程序,這裏叫作MyOAuth2Server。
3.1開始受權驗證
第一步,開始受權驗證,而且跳轉到指定的受權頁面。
先上代碼,而後再分析:
/// <summary> /// 第一步,開始受權驗證 /// 指定到用戶受權的頁面 /// </summary> /// <param name="client_id"></param> /// <param name="response_type"></param> /// <param name="redirect_uri"></param> /// <param name="state"></param> /// <param name="scope"></param> /// <returns></returns> public ActionResult Authorize(string client_id, string response_type, string redirect_uri, string scope, string state = "") { if ("code".Equals(response_type)) { //判斷client_id是否可用 if (!_oAuth2ServerServices.IsClientIdValied(client_id)) return this.Json("client_id 無效", JsonRequestBehavior.AllowGet); //保存用戶請求的全部信息到指定容器(session) Session.Add("client_id", client_id); Session.Add("response_type", response_type); Session.Add("redirect_uri", redirect_uri); Session.Add("state", state); Session.Add("scope", scope); //重定向到用戶受權頁面(固然你能夠自定義本身的頁面) return View("Authorize"); } return View("Error"); }
客戶端會受權會請求咱們受權驗證方法,
首先,驗證client_id是否可用,這裏的client_id是爲了保證安全性,確保請求端是服務端給予請求或者受權的權利。簡單地說,就是請求端在用此服務端以前要申請惟一的一個client_id;
而後,在把客戶端傳過來的信息保存在Session(你也能夠保存在其餘地方);
最後,跳轉到用戶操做的,是否給予受權的頁面(能夠是點擊一個肯定受權的按鈕,相似於微信受權。也能夠是輸入用戶名&密碼等的頁面)。
下面咱們看一下 return View("Authorize"); 這句代碼所返回給用戶許可的頁面:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>受權驗證</title> </head> <body> <div> 你肯定給用戶受權嗎? <form action="/OAuth2Server/Authenticate" method="post" id="login_form"> <br /><br /> <table class="form_field"> <tr> <td class="right"> User: </td> <td> <input type="text" name="user" id="user" style="width: 12em;"> </td> </tr> <tr> <td class="right"> Password: </td> <td> <input type="password" name="password" id="password" style="width: 12em;"> </td> </tr> <tr></tr> </table> <div class="action"> <input type="submit" value="受權" /> </div> <br /> </form> </div> </body> </html>
從上面能夠看到,用戶肯定受權後會提交信息到Authenticate方法,下面咱們看看Authenticate究竟是作了什麼。
3.2驗證並返回code到請求端
咱們這裏是用戶名與密碼驗證,固然你也能夠用其餘驗證。(好比用戶點擊一個受權容許的按鈕就能夠了)
首先,在OAuth2.0服務端上驗證用戶輸入的用戶名與密碼是否正確;
而後,生成code,而且設定code的生存時間,默認是30秒。(code只能用一次,以後要刪除);
再綁定code與用戶信息(用戶惟一鍵);
最後,重定向回redirect_uri請求的地址,而且返回code與state。(state是請求端那邊想要用於處理一些業務邏輯所用到的,固然能夠爲空)
上代碼
/// <summary> /// 第二步,用戶確認受權後的操做。 /// 用戶確認受權後,則返回code、access_token,並重定向到redirect_uri所指定的頁面 /// </summary> /// <returns></returns> public ActionResult Authenticate() { var username = Request["user"] ?? ""; var password = Request["password"] ?? ""; //取得重定向的信息 var redirect_uri = Session["redirect_uri"] ?? ""; var state = Session["state"] ?? ""; string code = TokenCodeUtil.GetCode(); //驗證用戶名密碼 if (!_oAuth2ServerServices.IsUserValied(username, password)) return this.Json("用戶名或密碼不正確", JsonRequestBehavior.AllowGet); //保存code到DB/Redis,默認存在30秒 _oAuth2ServerServices.SaveCode(code); //綁定code與userid,由於後面查詢用戶信息的時候要用到,默認存在30秒 _oAuth2ServerServices.BingCodeAndUser(username, code); //重定向 string url = string.Format(HttpUtility.UrlDecode(redirect_uri.ToString()) + "?code={0}&state={1}", code, state); Response.Redirect(url); return null; }
上面,已經完成了code的使命,而且返回到了請求端。
下面,咱們來看看怎麼獲取token。
3.3獲取token
在請求端獲取到code以後,請求端要獲取token,由於獲取了token請求端才能獲取到用戶信息等資料。
首先,把token設置成不能保持cache的狀態,爲了保證安全性;
而後,判斷是獲取token仍是刷新token的狀態;
再驗證code是否過時,驗證client_id、client_secret是否正確;
再生成token,把token存入容器(DB、Redis、Memory等)中;
在經過code來獲取用戶的信息,把用戶信息(主鍵)與token作綁定;
最後,把code刪除(code只能用一次,若是想再獲取token只能第一步開始從新作),返回token。
上代碼:
/// <summary> /// 獲取或刷新token。 /// token可能保存在DB/Redis等 /// </summary> /// <param name="code"></param> /// <param name="grant_type"></param> /// <param name="client_id"></param> /// <param name="client_secret"></param> /// <returns></returns> public ActionResult GetToken(string code, string grant_type, string client_id, string client_secret) { Response.ContentType = "application/json"; Response.AddHeader("Cache-Control", "no-store"); //獲取token if (grant_type == "authorization_code") { //判斷code是否過時 if (!_oAuth2ServerServices.IsCodeValied(code, DateTime.Now)) return this.Json("code 過時", JsonRequestBehavior.AllowGet); //判斷client_id與client_secret是否正確 if (!_oAuth2ServerServices.IsClientValied(client_id, client_secret)) return this.Json("client_id、client_secret不正確", JsonRequestBehavior.AllowGet); //新建token string access_token = TokenCodeUtil.GetToken(); //保存token,默認是30分鐘 _oAuth2ServerServices.SaveToken(access_token); //經過code獲取userid,而後用token與userid作綁定,最後把code設置成消失(刪除) string userId = _oAuth2ServerServices.GetUserIdFromCode(code); if (string.IsNullOrEmpty(userId)) return this.Json("code過時", JsonRequestBehavior.AllowGet); _oAuth2ServerServices.BingTokenAndUserId(access_token, userId); _oAuth2ServerServices.RemoveCode(code); //返回token return this.Json(access_token, JsonRequestBehavior.AllowGet); } //刷新token else if (grant_type == "refresh_token") { //新建token string new_access_token = TokenCodeUtil.GetToken(); //替換保存新的token,默認是30分鐘 //返回新建的token return this.Json(new_access_token, JsonRequestBehavior.AllowGet); } return this.Json("error grant_type=" + grant_type, JsonRequestBehavior.AllowGet); }
3.4經過token獲取用戶信息
上面請求端已經獲取到了token,因此這裏只須要驗證token,token驗證經過就直接返回用戶信息。
驗證token包括驗證是否存在、驗證是否過時。
/// <summary> /// 經過token獲取用戶信息 /// </summary> /// <param name="oauth_token"></param> /// <returns></returns> public ActionResult UserInfo(string oauth_token) { if(!_oAuth2ServerServices.IsTokenValied(oauth_token, DateTime.Now)) return this.Json("oauth_token無效", JsonRequestBehavior.AllowGet); UserInfo u = _oAuth2ServerServices.GetUserInfoFromToken(oauth_token); return this.Json(u, JsonRequestBehavior.AllowGet); }
4. 結語
到此,咱們寫OAuth2.0服務端的代碼已經結束了。
附上源碼:https://github.com/cjt321/MyOAuth2Server
下一篇將介紹請求端怎麼請求咱們的服務端,來測試流程、代碼是否正確:http://www.cnblogs.com/alunchen/p/6957785.html
能夠關注本人的公衆號,多年經驗的原創文章共享給你們。