如何在asp.mvc中处理请求之前启用基本身份验证? (里面的描述)

时间:2013-12-09 06:28:56

标签: c# asp.net-mvc-4 basic-authentication http-basic-authentication

我需要在开始处理之前验证传入的请求。当我的客户端应用程序向服务器请求时,我需要使用基本身份验证对请求进行身份验证,并且需要向客户端发送响应。

我尝试了以下但失败了,

public class OptionalAuthentication : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        HttpContextWrapper httpContext = new HttpContextWrapper(System.Web.HttpContext.Current);
        HttpRequestBase httpRequest = httpContext.Request;
        if ((httpContext.User == null ? true : !httpContext.User.Identity.IsAuthenticated))
        {
            var request = HttpContext.Current.Request;
            //request.Headers.FirstOrDefault(h => h.Key.Equals("Authorization"));
            var authHeader = request.Headers["Authorization"];
            if (authHeader != null)
            {
                var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);

                // RFC 2617 sec 1.2, "scheme" name is case-insensitive
                if (authHeaderVal.Scheme.Equals("basic",
                        StringComparison.OrdinalIgnoreCase) &&
                    authHeaderVal.Parameter != null)
                {
                    if (AuthenticateUser(authHeaderVal.Parameter))
                    {

                    }
                }
            }
        }
        else
        {
            //log.Trace("user is already authenticated: '{0}'", httpContext.User.Identity.Name);
        }
    }
}


[OptionalAuthentication]
    public ActionResult Index(string projectSlug, string repositoryName)
    {
        ActionResult emptyResult;
        if (Request.IsAuthenticated)
        {
            var cred = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(Request.Headers["Authorization"].Substring(6))).Split(':');
        }
    }

有人可以告诉我一种实现这一目标的方法。

1 个答案:

答案 0 :(得分:1)

这里给出了一个关于客户端

验证的demo

这里是关于控制器代码

   [HttpPost]
   public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            var userInfo = new UserInfo
            {
                UserName = model.UserName,
                Password = model.Password,
                //AppType = "Web"
            };

            var service = new ATWMSService();
            if(service.ValidateUser(userInfo))
            {
                Session["UserId"] = service.GetUserId(userInfo.UserName);
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                return Redirect("~/");
            }
            ModelState.AddModelError("","The user name or password provided is incorrect.");
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }