当面は基本認証を使用する web api プロジェクトを作成しました。nuget パッケージを使用して Web Api ヘルプ ドキュメントを生成したため、Web Api ヘルプの新しい領域、コントローラー、およびビューが追加されました。IIS で Web API をホストしています。現在、Web Api の URL " http://localhost/WebApi/Help "を参照するだけで、誰でも Web Api ヘルプを参照できます。ヘルプ ページ (MVC で実装されている) を認証する必要があります。ここでの質問は、Web API が基本認証を使用しており、Web API ヘルプ ページの要求の前に Web API ヘルプが認証されるようにメカニズムを作成したいということです。
これを実現するために、「AccountController」、「Login」ページを作成しました。また、認証フィルターを作成し、「HelpController」(ヘルプ ページを表示するためのすべてのアクションを含む) を装飾しました。ログインページコード:
public ActionResult Login(LoginViewModel model)
{
bool isValidated = //Code for validating the users
if (ModelState.IsValid && isValidated)
{
var identity = new HelpAuthenticationIdentity(model.UserName, model.Password);
var principal = new WindowsPrincipal(identity);
ControllerContext.HttpContext.User = principal;
return RedirectToAction("Index", "Help", new { area = "HelpPage" });
}
else
return View();
}
WindowsIdentity クラスを継承するアイデンティティ用のクラスを作成しました
public class HelpAuthenticationIdentity : WindowsIdentity
{
public HelpAuthenticationIdentity(string userName, string password)
: base(userName, "Basic")
{
this.Password = password;
}
public string Password { get; set; }
}
有効な資格情報を入力した後にログインをクリックすると、ヘルプコントローラーのインデックスアクションにリダイレクトされます。認証フィルターがあるので、最初に「OnAuthentication」メソッドを呼び出します。ここでは、常に「context.HttpContext.User.Identity.IsAuthenticated」フラグを false として取得しています。認証フィルタ属性は次のとおりです。
/// <summary>
/// Authentication filter to authenticate the request for Web Api Help
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class HelpAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext context)
{
if (!context.HttpContext.User.Identity.IsAuthenticated)
{
context.Result = new HttpUnauthorizedResult();
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext context)
{
if(context.Result == null || context.Result is HttpUnauthorizedResult)
{
context.Result = new RedirectToRouteResult("Login",
new System.Web.Routing.RouteValueDictionary{
{"controller", "Account"},
{"action", "Login"}
});
}
}
}
入力してください。