2014-01-20 127 views
1

我新的ASP.NET和休息...授權的Web API在asp.net MVC

我只是在做一個網站API2我的REST服務器已經準備就緒,並客戶端準備。

該API必須僅由有效用戶使用用戶名和密碼訪問。因此,它需要檢查的有效用戶,所以我試圖訪問用戶:

var uri = 'http://localhost/ProductsApp/api/products/username/password'; 

$(document).ready(function() { 
    // Send an AJAX request 
    $.getJSON(uri) 
     .done(function (data) { 
      // On success, 'data' contains a list of products. 
      $.each(data, function (key, item) { 
       // Add a list item for the product. 
       $('<li>', { text: formatItem(item) }).appendTo($('#products')); 
      }); 
     }); 
}); 

並就稱它爲訪問下面的方法:

public IEnumerable<Clients> GetAllClients(string username, string password) 
{ 

    //Here i tried to check the username and password 

    HttpRequestMessage message = new HttpRequestMessage(); 
    message.GetClientCertificate(); 
    return dbContext.Clients.ToList(); 
} 

但拋出錯誤。看來這不是這樣的方法。請你幫我介紹一個好的教程或解決這個問題......這將是非常有幫助的。

回答

0

通過實施webapi2的默認承載驗證的步行路程,可以發現here.

要註冊,你需要張貼到/ API /帳戶的用戶/註冊。正文將包含用戶名,密碼和ConfirmPassword屬性。

{ 
    'UserName': 'neil', 
    'Password': 'secretPassword', 
    'ConfirmPassword: 'secretPassword' 
} 

然後添加Content-Type:application/json作爲頭。

一旦你有一個註冊用戶,你可以通過發佈到/ Token並接收一個用於識別用戶的令牌來登錄它們。您需要將以下標題添加到這個帖子:

Content-Type: application/x-www-form-urlencoded 

而且身體會是這樣的:

grant_type=password&username=neil&password=secretPassword 

該職位將返回一個令牌。您需要將令牌作爲包含以下請求的標頭。標題看起來像:

Authorization: bearer xxx *where xxx is the token.*