ASP.NET Web API身份验证


122

我希望在使用ASP.NET Web API时从客户端应用程序对用户进行身份验证。我已经观看了网站上的所有视频,还阅读了该论坛帖子

[Authorize]正确放置属性将返回401 Unauthorized状态。但是,我需要知道如何允许用户登录到API。

我想从Android应用程序向API提供用户凭据,让用户登录,然后对所有后续API调用进行预身份验证。


嗨,Mujtaba。您能够实现这一点吗?
Vivek Chandraprakash13年

首先使用CORS来防止来自其他域的有害点击。然后发送一个有效的Forms Authentication cookie和请求,最后通过令牌授权请求。这种组合始终使您的Web API安全和优化。
Majedur Ra​​haman

Answers:


137

允许用户登录到API

您需要与请求一起发送有效的表单身份验证cookie。该cookie通常由服务器在LogOn通过调用[FormsAuthentication.SetAuthCookie方法进行身份验证(操作)时发送(请参阅MSDN)。

因此,客户需要执行2个步骤:

  1. LogOn通过发送用户名和密码向操作发送HTTP请求。反过来,此操作将调用FormsAuthentication.SetAuthCookie方法(如果凭据有效),该方法将在响应中设置表单身份验证cookie。
  2. [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.ClientMicrosoft.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"

是否要维护Android应用程序的会话?
Mujtaba Hassan 2012年

掌握了要点,但请您发布第二点的示例代码。感谢您的回答。
Mujtaba Hassan 2012年

2
编写Android HTTP客户端是另一个问题的主题。它与ASP.NET MVC和ASP.NET MVC Web API无关,这正是您的问题所在。我建议您启动一个用Java和Android显式标记的新线程,在其中询问如何编写使用cookie发送请求的HTTP客户端。
Darin Dimitrov

实际上,在MVC4 WebApi的文献中,他们已经写道WebAPI是第三方客户端(特别是移动客户端)的目标(当然也是如此)。假设我们有一个桌面应用程序客户端,请您发布一个简单的代码片段。谢谢
Mujtaba Hassan 2012年

2
也看到了这个问题(和答案)有关使用HTTP基本身份验证:stackoverflow.com/questions/10987455/...
吉姆·哈特

12

我以android为例。

public abstract class HttpHelper {

private final static String TAG = "HttpHelper";
private final static String API_URL = "http://your.url/api/";

private static CookieStore sCookieStore;

public static String invokePost(String action, List<NameValuePair> params) {
    try {
        String url = API_URL + action + "/";
        Log.d(TAG, "url is" + url);
        HttpPost httpPost = new HttpPost(url);
        if (params != null && params.size() > 0) {
            HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
            httpPost.setEntity(entity);
        }
        return invoke(httpPost);
    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }

    return null;
}

public static String invokePost(String action) {
    return invokePost(action, null);
}

public static String invokeGet(String action, List<NameValuePair> params) {
    try {
        StringBuilder sb = new StringBuilder(API_URL);
        sb.append(action);
        if (params != null) {
            for (NameValuePair param : params) {
                sb.append("?");
                sb.append(param.getName());
                sb.append("=");
                sb.append(param.getValue());
            }
        }
        Log.d(TAG, "url is" + sb.toString());
        HttpGet httpGet = new HttpGet(sb.toString());
        return invoke(httpGet);
    } catch (Exception e) {
        Log.e(TAG, e.toString());
    }

    return null;
}

public static String invokeGet(String action) {
    return invokeGet(action, null);
}

private static String invoke(HttpUriRequest request)
        throws ClientProtocolException, IOException {
    String result = null;
    DefaultHttpClient httpClient = new DefaultHttpClient();

    // restore cookie
    if (sCookieStore != null) {
        httpClient.setCookieStore(sCookieStore);
    }

    HttpResponse response = httpClient.execute(request);

    StringBuilder builder = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            response.getEntity().getContent()));
    for (String s = reader.readLine(); s != null; s = reader.readLine()) {
        builder.append(s);
    }
    result = builder.toString();
    Log.d(TAG, "result is ( " + result + " )");

    // store cookie
    sCookieStore = ((AbstractHttpClient) httpClient).getCookieStore();
    return result;
}

请注意:无法使用i.localhost。Android设备将localhost视为其本身的主机。ii。如果在IIS中部署Web API,则必须打开表单身份验证。


0

使用此代码并访问数据库

[HttpPost]
[Route("login")]
public IHttpActionResult Login(LoginRequest request)
{
       CheckModelState();
       ApiResponse<LoginApiResponse> response = new ApiResponse<LoginApiResponse>();
       LoginResponse user;
       var count = 0;
       RoleName roleName = new RoleName();
       using (var authManager = InspectorBusinessFacade.GetAuthManagerInstance())
       {
           user = authManager.Authenticate(request); 
       } reponse(ok) 
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.