在ASP.NET MVC 5基本身份验证 [英] Basic authentication in ASP.NET MVC 5
问题描述
必须做哪些步骤 ASP.NET MVC实现基本的身份验证 5?
我已阅读,OWIN不支持Cookie的身份验证,所以基本身份验证通常可能吗?
I have read that OWIN does not support cookieless authentication, so is basic authentication generally possible?
我是否需要自定义属性吗?我不知道这些属性是如何工作的。
Do I need a custom attribute here? I am not sure about how these attributes work.
推荐答案
您可以使用自定义属性ActionFilter使用这个简单而有效的机制:
You can use this simple yet effective mechanism using a custom ActionFilter attribute:
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();
}
}
它可以被用来在基本身份验证将整个控制器:
It can be used to put under Basic Authentication a whole controller:
[BasicAuthenticationAttribute("your-username", "your-password",
BasicRealm = "your-realm")]
public class HomeController : BaseController
{
...
}
或特定的ActionResult:
or a specific ActionResult:
public class HomeController : BaseController
{
[BasicAuthenticationAttribute("your-username", "your-password",
BasicRealm = "your-realm")]
public ActionResult Index()
{
...
}
}
您也可以 <一个href=\"http://www.ryadel.com/2014/12/08/http-basic-authentication-asp-net-mvc-using-custom-actionfilter/\"相对=nofollow>读到这里获取更多信息
You can also read here for more info.
这篇关于在ASP.NET MVC 5基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!