2012-04-13 3 views
1

Im создает собственный веб-сервис на основе 2-ного OAuth.Аутентификация HMAC в MVC3

С каждым аутентифицированным запросом будет включен HMAC.

Я знаю, что это можно сделать так:

public ActionResult userInfoExample(string HMAC, string username) 
    { 
     MyMembership.checkHMAC(HMAC); 
     //get user 
     return View(); 
    } 

но это довольно противно, потому что HMAC должна быть включена в параметры для каждого действия. Его слабо типизированный и дерьмо.

Я хотел сделать что-то вроде этого:

[AuthorizeHMAC] 
    public ActionResult userInfoExample(string username) 
    { 
     //get user 
     return View(); 
    } 

I found this, и он упоминал, что я должен смотреть на пользовательских модальных вяжущих, так что потом I found this и после его прочтения я не уверен, как я мог бы сделать эту работу.

Моя цель - аутентифицировать (/ разрешать) использование HMAC, которое (я полагаю) помещается в параметры URL-адреса, то есть: http: // www.website.com/foo/bar?username=xxx & hmac = xxxxxxxxx

Я хотел бы узнать, есть ли у кого-нибудь ссылки, которые я могу прочитать или прямое решение.
Я также приветствую критику на моем фундаментальном понимании безопасности API, или как я делаю вещи, я довольно новыми для этой области

ответ

1

Отъезд мой код на http://mvcsecurity.codeplex.com/

я сделать что-то подобное для проверки параметров на странице (хотя это не HMAC). Поскольку вы будете генерировать его в представлении Im Im (или передавая его в представление), вы можете проверить его таким же образом, как и в моем атрибуте.

От:

 

     public override void OnActionExecuting(ActionExecutingContext filterContext) 
     { 
      //The hidden form field that contains our hash - for ex. CustomerId is rendered as a hidden input id="_CustomerIdToken" 
      string encryptedPropertyName = string.Format("_{0}Token", _propertyName); 

      //grab the token 
      string hashToken = filterContext.HttpContext.Request.Form[encryptedPropertyName]; 

      //The encrypted form data MUST be there. We do not allow empty strings otherwise this could give 
      //an attack vector in our filter as a means to bypass checks by simply passing in an empty validation token. 
      if (string.IsNullOrEmpty(hashToken)) 
      { 
       throw new MissingFieldException(string.Format("The hidden form field named value {0} was missing. This is created by the Html.AntiModelInjection methods. Ensure the name used on your [ValidateAntiModelInjectionAttribute(\"!HERE!\")] matches the field name used in Html.AntiModelInjection method. If this attribute is used on a controller method that is meant for HttpGet, then the form value would not yet exist. This attribute is meant to be used on controller methods accessed via HttpPost.", encryptedPropertyName)); 
      } 


      //Get the plain text value 
      string formValue = filterContext.HttpContext.Request.Form[_propertyName]; 

      //Plain text must be available to compare. 
      if (string.IsNullOrEmpty(formValue)) 
      { 
       throw new MissingFieldException(string.Format("The form value {0} was missing. If this attribute is used on a controller method that is meant for HttpGet, then the form value would not yet exist. This attribute is meant to be used on controller methods accessed via HttpPost.", _propertyName)); 
      } 


      //We cannot encrypt the form value and compare to the previously encrypted form token. 
      //Each time you Encrypt() with the MachineKey class even using the same plain text, the end result is difference. 
      byte[] plainTextBytes = MachineKey.Decode(hashToken, MachineKeyProtection.Encryption); 

      string plainText = Encoding.Unicode.GetString(plainTextBytes); 

      //And compare 
      if (string.Compare(plainText, formValue , false, CultureInfo.InvariantCulture) != 0) 
      { 
       throw new HttpAntiModelInjectionException(string.Format("Failed security validation for {0}. It is possible the data was tampered with as the original value used to create the form field does not match the current property value for this field. Ensure if this is a web farm, the machine keys are the same.",_propertyName)); 
      } 


      filterContext.HttpContext.Trace.Write("(Logging Filter)Action Executing: " + 
       filterContext.ActionDescriptor.ActionName); 

      base.OnActionExecuting(filterContext); 
     } 
 
+0

Этот сайт является довольно запутанной. Можете ли вы опубликовать фрагмент связанного кода здесь? (также я нахожусь на своем планшете, поэтому мне нечего его просматривать). – MrJD

+0

Источник находится по адресу: http://mvcsecurity.codeplex.com/SourceControl/changeset/view/13151#149140 соответствующий раздел, размещенный выше, чтобы прочитать значение формы в атрибуте –

+0

+1 для вашего времени. Я попробую сегодня посмотреть, работает ли это – MrJD

Смежные вопросы