ASP.NET MVC - HTTP Authentication Prompt

后端 未结 4 2119
轮回少年
轮回少年 2020-11-28 04:44

Is it possible to make my application ask for username and password prompting for it before render a view? Just like on twitter API to get information about your account:

4条回答
  •  余生分开走
    2020-11-28 05:24

    Well, to require basic authentication you need to return 401 status code. But doing that will cause the current authentication module to execute its default unauthorized handler (for forms authentication, this means redirecting to login page).

    I wrote an ActionFilterAttribte to see if I can get the behaviour you want when there's no authentication module installed in web.config.

    public class RequireBasicAuthentication : ActionFilterAttribute {
       public override void OnActionExecuting(ActionExecutingContext filterContext) {
           var req = filterContext.HttpContext.Request;
           if (String.IsNullOrEmpty(req.Headers["Authorization"])) {
               var res = filterContext.HttpContext.Response;
               res.StatusCode = 401;
               res.AddHeader("WWW-Authenticate", "Basic realm=\"Twitter\"");
               res.End();
           }
       }
    }
    

    And the controller action :

    [RequireBasicAuthentication]
    public ActionResult Index() {
        var cred = System.Text.ASCIIEncoding.ASCII
                .GetString(Convert.FromBase64String(
                Request.Headers["Authorization"].Substring(6)))
                .Split(':');
        var user = new { Name = cred[0], Pass = cred[1] };
        return Content(String.Format("user:{0}, password:{1}", 
            user.Name, user.Pass));
    }
    

    That action successfully prints the username and password I enter. But I really doubt that's the best way to do this. Do you have no choice except asking for username and password this way?

提交回复
热议问题