cho phép người dùng đăng nhập vào API
Bạn cần phải gửi một cookie hình thức xác thực hợp lệ cùng với yêu cầu. Cookie này thường được máy chủ gửi khi xác thực (LogOn
hành động) bằng cách gọi phương thức [FormsAuthentication.SetAuthCookie
(xem MSDN).
Vì vậy, khách hàng cần thực hiện 2 bước sau:
- Gửi một yêu cầu HTTP đến một hành động
LogOn
bằng cách gửi tên người dùng và mật khẩu. Lần lượt hành động này sẽ gọi phương thức FormsAuthentication.SetAuthCookie
(trong trường hợp thông tin đăng nhập hợp lệ), điều này sẽ lần lượt thiết lập cookie xác thực biểu mẫu trong phản hồi.
- Gửi yêu cầu HTTP đến
[Authorize]
hành động được bảo vệ bằng cách gửi cùng cookie xác thực biểu mẫu mà nó đã truy lục trong yêu cầu đầu tiên.
Hãy lấy một ví dụ. Giả sử rằng bạn có 2 bộ điều khiển API được định nghĩa trong ứng dụng web của bạn:
Đầu tiên một trách nhiệm xử lý xác thực:
public class AccountController : ApiController
{
public bool Post(LogOnModel model)
{
if (model.Username == "john" && model.Password == "secret")
{
FormsAuthentication.SetAuthCookie(model.Username, false);
return true;
}
return false;
}
}
và điều thứ hai chứa các hành động bảo vệ mà người dùng chỉ được ủy quyền có thể thấy:
[Authorize]
public class UsersController : ApiController
{
public string Get()
{
return "This is a top secret material that only authorized users can see";
}
}
Bây giờ chúng tôi có thể viết một ứng dụng khách hàng tiêu thụ API này. Dưới đây là một tầm thường ví dụ giao diện điều khiển ứng dụng (chắc chắn rằng bạn đã cài đặt Microsoft.AspNet.WebApi.Client
và Microsoft.Net.Http
gói NuGet):
using System;
using System.Net.Http;
using System.Threading;
class Program
{
static void Main()
{
using (var httpClient = new HttpClient())
{
var response = httpClient.PostAsJsonAsync(
"http://localhost:26845/api/account",
new { username = "john", password = "secret" },
CancellationToken.None
).Result;
response.EnsureSuccessStatusCode();
bool success = response.Content.ReadAsAsync<bool>().Result;
if (success)
{
var secret = httpClient.GetStringAsync("http://localhost:26845/api/users");
Console.WriteLine(secret.Result);
}
else
{
Console.WriteLine("Sorry you provided wrong credentials");
}
}
}
}
Và dưới đây là cách 2 yêu cầu HTTP nhìn vào dây:
xác thực yêu cầu:
POST /api/account HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: localhost:26845
Content-Length: 39
Connection: Keep-Alive
{"username":"john","password":"secret"}
Phản hồi xác thực:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Wed, 13 Jun 2012 13:24:41 GMT
X-AspNet-Version: 4.0.30319
Set-Cookie: .ASPXAUTH=REMOVED FOR BREVITY; path=/; HttpOnly
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: application/json; charset=utf-8
Content-Length: 4
Connection: Close
true
Yêu cầu đối với dữ liệu được bảo vệ:
GET /api/users HTTP/1.1
Host: localhost:26845
Cookie: .ASPXAUTH=REMOVED FOR BREVITY
đáp ứng cho dữ liệu được bảo vệ:
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Wed, 13 Jun 2012 13:24:41 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: application/json; charset=utf-8
Content-Length: 66
Connection: Close
"This is a top secret material that only authorized users can see"
Hi Mujtaba. Bạn có thể thực hiện việc này không? –