/// <summary> /// 驗證邏輯 /// </summary> /// <param name="context"></param> /// <returns></returns> public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { #region 推播key Set context.OwinContext.Set <string>("as:KeyNumber", context.Parameters.Get("KeyNumber")); context.OwinContext.Set <string>("as:MobileType", context.Parameters.Get("MobileType")); #endregion #region Client Logic string clientId = string.Empty; string clientSecret = string.Empty; Client client = null; //從header的authorization欄位中取得Base 64編碼後的Client id 和 secret, //另一方式為client_id/client_secret以x-www-form-urlencoded傳送 if (!context.TryGetBasicCredentials(out clientId, out clientSecret)) { context.TryGetFormCredentials(out clientId, out clientSecret); } //Client端若未配置ClientId則回傳錯誤 if (context.ClientId == null) { context.Validated(); return(Task.FromResult <object>(null)); } //收到ClientId後檢查資料庫,如果ClientId未記錄在資料庫中將拒絕這個請求。 using (AuthBLL _auth = new AuthBLL()) { client = _auth.FindClient(context.ClientId); } if (client == null) { context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId)); return(Task.FromResult <object>(null)); } //檢查客戶端的應用程式, //如果為Java Script則為非機密型應用程式,我們將不檢查或要求加密證書 //如果是Native應用程式,就必須強制要求加密證書 if (client.ApplicationType == ApplicationTypes.NativeConfidential) { if (string.IsNullOrWhiteSpace(clientSecret)) { context.SetError("invalid_clientId", "Client secret should be sent."); return(Task.FromResult <object>(null)); } else { if (client.Secret != Helper.GetHash(clientSecret)) { context.SetError("invalid_clientId", "Client secret is invalid."); return(Task.FromResult <object>(null)); } } } //檢查Client的存活期,如果不在存活期內則回應無效 if (!client.Active) { context.SetError("invalid_clientId", "Client is inactive."); return(Task.FromResult <object>(null)); } //存儲的客戶端允許的生成 context.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin); //更新Token生命時間值,生成新Token後設定到期時間 context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString()); #endregion context.Validated(); return(Task.FromResult <object>(null)); }