本当に安全な認証オプションが必要な場合は、OAuthのような方法があります。このblog postは、現在廃止されたWCF Web APIを使用してかなり徹底したサンプルを提供していますが、多くのコードが救済可能です。あるいは、少なくともblog postのようにHTTP基本認証を使用してください。 Aliostadが指摘しているように、トークンが安全な状態になるように基本認証ルートに行く場合は、HTTPSを使用していることを確認してください。
あなたが自分自身をロールすることを決めた場合(ほとんどの場合、上記のいずれのオプションよりも安全性が低くなります)、HTTPヘッダルートに行く場合、AuthorizationHanlderに必要なコードサンプルがあります。 UserPrimicipalがWeb APIクラスで処理される方法が変更される可能性が高いことに注意してください。このコードは最初のプレビューリリースにのみ適しています。あなたはワイヤーでAuthorizationHandlerこのようにする必要があります:
GlobalConfiguration.Configuration.MessageHandlers.Add(new AuthenticationHandler());
ヘッダ・トークンのためのコード:
public class AuthenticationHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var requestAuthTokenList = GetRequestAuthTokens(request);
if (ValidAuthorization(requestAuthTokenList))
{
//TODO: implement a Prinicipal generator that works for you
var principalHelper = GlobalConfiguration.Configuration
.ServiceResolver
.GetService(typeof(IPrincipalHelper)) as IPrincipalHelper;
request.Properties[HttpPropertyKeys.UserPrincipalKey] =
principalHelper.GetPrinicipal(request);
return base.SendAsync(request, cancellationToken);
}
/*
** This will make the whole API protected by the API token.
** To only protect parts of the API then mark controllers/methods
** with the Authorize attribute and always return this:
**
** return base.SendAsync(request, cancellationToken);
*/
return Task<HttpResponseMessage>.Factory.StartNew(
() => new HttpResponseMessage(HttpStatusCode.Unauthorized)
{
Content = new StringContent("Authorization failed")
});
}
private static bool ValidAuthorization(IEnumerable<string> requestAuthTokens)
{
//TODO: get your API from config or however makes sense for you
var apiAuthorizationToken = "good token";
var authorized = requestAuthTokens.Contains(apiAuthorizationToken);
return authorized;
}
private static IEnumerable<string> GetRequestAuthTokens(HttpRequestMessage request)
{
IEnumerable<string> requestAuthTokens;
if (!request.Headers.TryGetValues("SomeHeaderApiKey", out requestAuthTokens))
{
//Initialize list to contain a single not found token:
requestAuthTokens = new[] {"No API token found"};
}
return requestAuthTokens;
}
}
あなたはAPIトークンとはどういう意味ですか?認証Cookieを意味しますか? – Aliostad
クライアントを認証するための各要求で渡すことができるGUIDです。 – jaffa