5

我正在使用新的webapi。嘗試解密FormsAuthentication憑單始終無法驗證數據

現在我不知道我是否正確地做到了這一點,但我試圖設置我的API以返回HttpResponseMessages頭中的身份驗證cookie,以便在另一個mvc應用程序上使用。

我用的FormsAuthenticationTicket,因爲我認爲它我需要什麼樣

public HttpResponseMessage Get(LoginModel model) 
    { 
     if (model.UserName == "bob") 
     { 
      // if (Membership.ValidateUser(model.UserName, model.Password)) 
      // { 
      var msg = new HttpResponseMessage(HttpStatusCode.OK); 
      var expires = DateTime.Now.AddMinutes(30); 
      var auth = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, expires, 
                model.RememberMe,"password", 
                FormsAuthentication.FormsCookiePath); 
      var cookie = new HttpCookie("user"); 
      cookie.Value = FormsAuthentication.Encrypt(auth); 
      cookie.Domain = "localhost"; 
      cookie.Expires = expires; 
      msg.Headers.Add("result",cookie.Value); 
      return msg; 
      // } 
     } 
     return new HttpResponseMessage(HttpStatusCode.Forbidden); 
     //else 
     //{ 
     // return "The user name or password provided is incorrect."; 
     //} 
    } 
現在

我登錄控制器內使用我的MVC應用程序,我調用服務,並從我設置在標題中的數據值api控制器。

string data = response.Headers["result"].ToString(); 
    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(data); 

每次我嘗試運行FormsAuthentication.Decrypt我不斷收到一個錯誤

無法驗證數據。

我認爲,當api加密數據時,它會使用某種網站不知道的密鑰。我對嗎?

有人可以幫忙嗎?

謝謝

+0

此行中'data'的值是什麼id string = response.Headers [「result」]。ToString();'? – Aliostad 2012-04-12 08:40:34

回答

8

我認爲它是由於當API加密它使用關鍵的是,網站不知道的某種 數據。我對嗎?

FormsAuthentication.Encrypt和Decrypt方法使用machine key。因此,請確保您爲Web API Web應用程序和使用的ASP.NET MVC應用程序配置了相同的密鑰。

您也可以查看following article,它說明了如何將OAuth 2.0與Web API一起使用。

+0

任何想法如何拋出一個錯誤,以便我可以清除我的cookie並將用戶從異常重定向到控制器?我的cookies持續存在,因此我陷入了重定向循環。當我更新密鑰時會發生這種情況。 Web API返回401,但MVC重定向到登錄頁面,並且登錄頁面請求再次發回cookie,引發未經授權的響應。陷入惡性循環! – Shouvik 2014-11-14 16:02:58