ASP.NET Web API 身份验证 [英] ASP.NET Web API Authentication
问题描述
我希望在使用 ASP.NET Web API.我已经观看了网站上的所有视频,还阅读了 此论坛帖子.
I am looking to authenticate a user from a client application while using the ASP.NET Web API. I have watched all the videos on the site and also read this forum post.
正确放置 [Authorize]
属性会返回 401 Unauthorized
状态.但是,我需要知道如何允许用户登录 API.
Putting the [Authorize]
attribute correctly returns a 401 Unauthorized
status. However, I need to know how to allow a user to log in to the API.
我想从 Android 应用程序向 API 提供用户凭据,让用户登录,然后对所有后续 API 调用进行预身份验证.
I want to provide user credentials from an Android application to the API, get the user logged in, and then have all subsequent API calls pre-authenticated.
推荐答案
允许用户登录 API
allow a user to log in to the API
您需要随请求一起发送有效的表单身份验证 cookie.此 cookie 通常由服务器在通过调用 [FormsAuthentication.SetAuthCookie
方法进行身份验证(LogOn
操作)时发送(请参阅 MSDN).
You need to send a valid Forms Authentication cookie along with the request. This cookie is usually sent by the server when authenticating (LogOn
action) by calling the [FormsAuthentication.SetAuthCookie
method (see MSDN).
所以客户端需要执行两个步骤:
So the client needs to perform 2 steps:
- 通过发送用户名和密码向
LogOn
操作发送 HTTP 请求.反过来,此操作将调用FormsAuthentication.SetAuthCookie
方法(如果凭据有效),该方法又将在响应中设置表单身份验证 cookie. - 将 HTTP 请求发送到
[Authorize]
受保护的操作,方法是发送它在第一个请求中检索到的表单身份验证 cookie.
- Send an HTTP request to a
LogOn
action by sending the username and password. In turns this action will call theFormsAuthentication.SetAuthCookie
method (in case the credentials are valid) which in turn will set the forms authentication cookie in the response. - Send an HTTP request to an
[Authorize]
protected action by sending along the forms authentication cookie it retrieved in the first request.
让我们举个例子.假设您在 Web 应用程序中定义了 2 个 API 控制器:
Let's take an example. Suppose that you have 2 API controllers defined in your web application:
第一个负责处理身份验证的:
The first one responsible for handling authentication:
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;
}
}
第二个包含只有授权用户才能看到的受保护操作:
and the second one containing protected actions that only authorized users can see:
[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
NuGet 包):
Now we could write a client application consuming this API. Here's a trivial console application example (make sure you have installed the Microsoft.AspNet.WebApi.Client
and Microsoft.Net.Http
NuGet packages):
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 请求在网络上的样子:
And here's how the 2 HTTP requests look on the wire:
身份验证请求:
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"
这篇关于ASP.NET Web API 身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!