2018年9月20日

(C#) - Basic Authentication + Form Authentication

因在Azure上發布了測試版網頁,但不希望被外部使用者搜尋到或者是看到,因此加上登入的機制來限制瀏覽


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();
        }
    }



接著在controller或者是Action上方加上attributes來限制存取

[BasicAuthenticationAttribute("account", "Password", BasicRealm = "Domain")]


Reference:
https://stackoverflow.com/questions/20144364/basic-authentication-in-asp-net-mvc-5/27348911#27348911

沒有留言:

張貼留言

<Javascript> How to uncompressed GZIP at front-end using Javascript

It's been a while I haven't share my coding work. In this article I would like to share how to receive a Gzip file via stream, unzip...