簡體   English   中英

WebAPI(MVC4)中的授權

[英]Authorization in WebAPI (MVC4)

我們的客戶已為我安排了以下任務:

使其經過身份驗證的用戶無法修改其他用戶的信息

當前,電話應用程序通過HTTPS向我們的API發送用戶名和密碼,作為BASIC身份驗證標頭:base64(username:password)。

在WebAPI中,我創建了BasicAuthenticationMessageHandler。 在此處理程序中,我針對客戶LDAP驗證用戶憑據。

這一切都很好。

我有一個稱為客戶的控制器:

[Authorize]
public class CustomerController : BaseApiController<CustomerMapper>
{ ... }

我用如上所示的Authorize屬性裝飾它。

我有這樣的PUT方法:

    public HttpResponseMessage Put(CustomerPutModel data)
    {
        if (ModelState.IsValid)
        {
            var c = customerService.GetByID(data.ID);

            if (c != null)
            {
                c = ModelMapper.Map<CustomerPutModel, Customer>(data, c);

                customerService.Update(c);

                return new HttpResponseMessage(HttpStatusCode.NoContent);
            }
        }
        throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
    }

模型:

public class CustomerPutModel
{
    public int ID{ get; set; }
    [Required]
    public string CustomerAccountID { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    [Required]
    public string City { get; set; }
    [Required]
    public string State { get; set; }
    public int Zipcode { get; set; }
}

此控制器方法按預期方式工作。

我遇到問題的地方是如何在我的PUT方法(以及所有其他控制器/方法)中防止以下情況:

  1. 用戶1具有正確的身份驗證憑據
  2. 用戶1使用代理來監聽請求
  3. 用戶1將請求正文的ID從其ID更改為用戶2的ID
  4. 用戶1發送帶有正確身份驗證標頭的PUT,但在正文中,他們傳遞了另一個用戶ID

如何在方法級別防止這種情況? 由於應用程序的不同部分遇到了某些控制器操作,因此我認為我無法保護所有這些操作。

授權經過身份驗證的用戶實際上可以執行他們請求的操作的正確方法是什么? 是否需要為每個方法操作自定義編碼?

我建議創建簽名以驗證請求是否被篡改,這意味着您根據應用程序發送的信息使用某種單向加密算法。

在API上收到請求時,只需使用相同的算法即可接收信息,並查看簽名是否匹配。 如果不是,則有人篡改了請求並修改了一些信息。

只要進行一些防止篡改請求的研究即可。

關於確保用戶只能執行某些方法而不能執行其他方法,例如,我建議您研究基於聲明的授權。

您可以將Action方法更改為以下內容:

public HttpResponseMessage Put(CustomerPutModel data)
{
    if (ModelState.IsValid)
    {
        var myID = userService.GetIDByUserName(HttpContext.Current.User.Identity.Name);
        if (myID != data.ID) 
        {
            ... wrong id, e.g. throw an exception or return a View indicating the error.
        }
        var c = customerService.GetByID(data.ID);

        if (c != null)
        {
            c = ModelMapper.Map<CustomerPutModel, Customer>(data, c);

            customerService.Update(c);

            return new HttpResponseMessage(HttpStatusCode.NoContent);
        }
    }
    throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.BadRequest));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM