基本認証を使用しているWeb APIプロジェクトを作成しました。私たちはWeb Apiヘルプドキュメントを生成するためにnugetパッケージを使用していますので、Web Apiヘルプの新しい領域、コントローラ、およびビューを追加しました。 IISでWeb APIをホストしました。今すぐ、Web ApiのURL「」をブラウズするだけで、Web APIのヘルプを閲覧することができます。 ヘルプページ(MVCに実装されています)を認証します。ここでの質問は、私のWeb APIは基本認証を使用しており、Web APIヘルプページのリクエスト前にWeb APIヘルプが認証されるようにメカニズムを作成したいのです。有効なユーザーだけがWeb APIドキュメントを閲覧できるようにWebページの後ろに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();
}
は私が
public class HelpAuthenticationIdentity : WindowsIdentity
{
public HelpAuthenticationIdentity(string userName, string password)
: base(userName, "Basic")
{
this.Password = password;
}
public string Password { get; set; }
}
私は有効な資格情報を入力した後、ログインをクリックして、それがインデックスアクションにリダイレクトされますWindowsIdentityクラスを継承するアイデンティティのためのクラスを作成しましたヘルプコントローラです。私は認証フィルターを持っているので、まず "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"}
});
}
}
}
入力してください。