私はMVC 4 Web APIを使用しており、サービスを使用する前にユーザーを認証します。フォーム認証を使用したサービス認証のためにWeb ApiでApi keyを使用する方法
私は認可メッセージハンドラを実装しました。これはうまく動作します。
public class AuthorizationHandler : DelegatingHandler
{
private readonly AuthenticationService _authenticationService = new AuthenticationService();
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
IEnumerable<string> apiKeyHeaderValues = null;
if (request.Headers.TryGetValues("X-ApiKey", out apiKeyHeaderValues))
{
var apiKeyHeaderValue = apiKeyHeaderValues.First();
// ... your authentication logic here ...
var user = _authenticationService.GetUserByKey(new Guid(apiKeyHeaderValue));
if (user != null)
{
var userId = user.Id;
var userIdClaim = new Claim(ClaimTypes.SerialNumber, userId.ToString());
var identity = new ClaimsIdentity(new[] { userIdClaim }, "ApiKey");
var principal = new ClaimsPrincipal(identity);
Thread.CurrentPrincipal = principal;
}
}
return base.SendAsync(request, cancellationToken);
}
}
問題は、フォーム認証を使用していることです。
[HttpPost]
public ActionResult Login(UserModel model)
{
if (ModelState.IsValid)
{
var user = _authenticationService.Login(model);
if (user != null)
{
// Add the api key to the HttpResponse???
}
return View(model);
}
return View(model);
}
私は私のAPIを呼び出す:
[Authorize]
public class TestController : ApiController
{
public string GetLists()
{
return "Weee";
}
}
ハンドラはX-APIKEYヘッダーを見つけることができません。
ユーザーがログインしている限り、http応答ヘッダーにユーザーのapiキーを追加し、そこにキーを保持する方法はありますか? この機能を実装する別の方法はありますか?
ありがとうございます!あなたは正しいです、私はフォーム認証を意味しています。私は私の質問を編集しました。私はメンバーシッププロバイダを使用していませんが、代わりにカスタム認証ロジックを作成しました。 HttpRequestMessageを使用することはできません。なぜなら、私はMVC Controllerを使用して認証を行い、アクション結果を返すため(または私はそれを使用する方法がわかりません)。 –