Basic authentication in ASP.NET MVC 5

前端 未结 7 1899
执念已碎
执念已碎 2020-12-07 13:58

What steps must be done to implement basic authentication in ASP.NET MVC 5?

I have read that OWIN does not support cookieless authentication, so is basic authenticat

7条回答
  •  一生所求
    2020-12-07 14:28

    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
    {
       ...
    }
    

    or a specific ActionResult:

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

    In case you need additional info check out this blog post that I wrote on the topic.

提交回复
热议问题