0

我有一個內部使用網站,它將通過Internet進行公開,以便在移動設備上使用。該網站是MVC 5,並將與不同服務器上的Web API進行通信。用戶將在登錄頁面上輸入他們的Windows帳戶信息,該信息將通過我們的Active Directory服務進行驗證。一旦通過身份驗證,我想創建一個身份驗證令牌,用於隨後調用MVC網站以及調用各種其他Web API。如何在Web API中使用Google樣式令牌驗證

起初我們只打算使用基本認證,因爲所有通信渠道都是通過SSL進行的,但是我們有一個Web API不能訪問我們的AD,但可以訪問可能包含令牌信息的中央數據庫。

有關如何保護企業Web API的任何示例或文檔都很棒。我無法找到關於此主題的許多信息。

回答

0

做到這將是創建一個自定義ActionFilterAttribute並重寫OnActionExecuting法的方式進行。

public class AuthenticateAttribute : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(HttpActionContext actionContext) 
    { 
      //grab token from httprequest in the actionContext 
      //and authenticate it against the token in the database 

     if(/*token is NOT authenticated*/) 
     { 
       //set unauthorised response 
       var response = actionContext.ControllerContext.Request.CreateResponse(HttpStatusCode.Unauthorized); 
      //and set the httpresponse in the actionContext to the unauthorised response 
      actionContext.Response = response; 
      //then return 
      return; 
     } 
    } 
} 

然後,您可以將此屬性應用於您希望驗證的api中的任何操作或方法。

相關問題