122

ASP.NET Web APIを使用しているときに、クライアント アプリケーションからユーザーを認証しようとしています。このサイトのすべてのビデオを視聴し、このフォーラムの投稿も読みました。

属性[Authorize]を正しく配置すると、401 Unauthorizedステータスが返されます。ただし、ユーザーが API にログインできるようにする方法を知る必要があります。

Android アプリケーションから API にユーザー資格情報を提供し、ユーザーをログインさせ、その後のすべての API 呼び出しを事前認証したいと考えています。

4

3 に答える 3

137

ユーザーがAPIにログインできるようにする

リクエストと一緒に有効なフォーム認証Cookieを送信する必要があります。このCookieは通常、メソッドLogOnを呼び出して認証(アクション)するときにサーバーによって送信されます( MSDNを参照)。[FormsAuthentication.SetAuthCookie

したがって、クライアントは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;
    }
}

2つ目は、許可されたユーザーのみが表示できる保護されたアクションを含みます。

[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.HttpNuGetパッケージがインストールされていることを確認してください)。

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"
于 2012-06-13T12:41:58.380 に答える
12

例としてアンドロイドを取り上げます。

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 をデプロイする場合は、フォーム認証を開く必要があります。

于 2013-04-26T13:52:58.553 に答える
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) 
}
于 2016-12-05T09:46:20.633 に答える