2014-01-20 131 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.*