ASP.NET Web APIを使用しながら、クライアントアプリケーションからユーザーを認証しようとしています。私はサイトのすべてのビデオを見て、このフォーラムの投稿も読んだ。
置く[Authorize]属性が正しく返す401 Unauthorized状況を。ただし、ユーザーがAPIにログインできるようにする方法を知る必要があります。
AndroidアプリケーションからAPIにユーザー認証情報を提供し、ユーザーをログインさせて、その後のすべてのAPI呼び出しを事前認証したいと思います。
ASP.NET Web APIを使用しながら、クライアントアプリケーションからユーザーを認証しようとしています。私はサイトのすべてのビデオを見て、このフォーラムの投稿も読んだ。
置く[Authorize]属性が正しく返す401 Unauthorized状況を。ただし、ユーザーがAPIにログインできるようにする方法を知る必要があります。
AndroidアプリケーションからAPIにユーザー認証情報を提供し、ユーザーをログインさせて、その後のすべてのAPI呼び出しを事前認証したいと思います。
回答:
ユーザーがAPIにログインできるようにする
リクエストと共に有効なフォーム認証Cookieを送信する必要があります。このCookieは通常LogOn、[FormsAuthentication.SetAuthCookieメソッドを呼び出して認証(アクション)するときにサーバーによって送信されます(MSDNを参照)。
したがって、クライアントは2つのステップを実行する必要があります。
LogOnユーザー名とパスワードを送信して、HTTPリクエストをアクションに送信します。次に、このアクションはFormsAuthentication.SetAuthCookieメソッドを呼び出し(資格情報が有効な場合)、応答でフォーム認証Cookieを設定します。[Authorize]最初のリクエストで取得したフォーム認証Cookieを送信して、保護されたアクションにHTTPリクエストを送信します。例を見てみましょう。Webアプリケーションで2つのAPIコントローラーが定義されているとします。
認証の処理を担当する最初の1つ:
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;
}
}
もう1つは、許可されたユーザーのみが表示できる保護されたアクションを含みます。
[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"
私は例としてアンドロイドを取ります。
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をデプロイする場合は、フォーム認証を開く必要があります。
このコードを使用してデータベースにアクセスする
[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)
}