允许用户登录到API
您需要与请求一起发送有效的表单身份验证cookie。该cookie通常由服务器在LogOn
通过调用[FormsAuthentication.SetAuthCookie
方法进行身份验证(操作)时发送(请参阅MSDN)。
因此,客户需要执行2个步骤:
LogOn
通过发送用户名和密码向操作发送HTTP请求。反过来,此操作将调用FormsAuthentication.SetAuthCookie
方法(如果凭据有效),该方法将在响应中设置表单身份验证cookie。
[Authorize]
通过发送在第一个请求中检索到的表单身份验证cookie,将HTTP请求发送到受保护的操作。
让我们举个例子。假设您在Web应用程序中定义了2个API控制器:
第一个负责处理身份验证的人:
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;
}
}
第二个包含受保护的操作,只有授权用户才能看到:
[Authorize]
public class UsersController : ApiController
{
public string Get()
{
return "This is a top secret material that only authorized users can see";
}
}
现在我们可以编写一个使用此API的客户端应用程序。这是一个简单的控制台应用程序示例(确保已安装Microsoft.AspNet.WebApi.Client
和Microsoft.Net.Http
)。
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");
}
}
}
}
这是2个HTTP请求在网络上的外观:
认证请求:
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"}
身份验证响应:
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
要求保护的数据:
GET /api/users HTTP/1.1
Host: localhost:26845
Cookie: .ASPXAUTH=REMOVED FOR BREVITY
对受保护数据的响应:
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"