Asp.net

ASP.NET MVC 5 中的基本身份驗證

  • November 22, 2013

在ASP.NET MVC 5中實現基本身份驗證必須執行哪些步驟?

我讀過 OWIN 不支持無 cookie 身份驗證,那麼基本身份驗證通常是可能的嗎?

我需要一個自定義屬性嗎?我不確定這些屬性是如何工作的。

您可以使用自定義 ActionFilter 屬性來使用這種簡單而有效的機制:

public class BasicAuthenticationAttribute : ActionFilterAttribute
{
   public string BasicRealm { get; set; }
   protected string Username { get; set; }
   protected string Password { get; set; }

   public BasicAuthenticationAttribute(string username, string password)
   {
       this.Username = username;
       this.Password = password;
   }

   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
       var req = filterContext.HttpContext.Request;
       var auth = req.Headers["Authorization"];
       if (!String.IsNullOrEmpty(auth))
       {
           var cred = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(auth.Substring(6))).Split(':');
           var user = new { Name = cred[0], Pass = cred[1] };
           if (user.Name == Username && user.Pass == Password) return;
       }
       filterContext.HttpContext.Response.AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Ryadel"));
       /// thanks to eismanpat for this line: http://www.ryadel.com/en/http-basic-authentication-asp-net-mvc-using-custom-actionfilter/#comment-2507605761
       filterContext.Result = new HttpUnauthorizedResult();
   }
}

它可用於將整個控制器置於基本身份驗證之下:

[BasicAuthenticationAttribute("your-username", "your-password", 
   BasicRealm = "your-realm")]
public class HomeController : BaseController
{
  ...
}

或特定的 ActionResult:

public class HomeController : BaseController
{
   [BasicAuthenticationAttribute("your-username", "your-password", 
       BasicRealm = "your-realm")]
   public ActionResult Index() 
   {
       ...
   }
}

如果您需要更多資訊,請查看我就該主題撰寫的這篇博文。

引用自:https://stackoverflow.com/questions/20144364