【问题标题】:Web API Authentication (without asp.net identity)Web API 身份验证(无 asp.net 身份)
【发布时间】:2017-10-22 22:31:00
【问题描述】:

是否可以在不使用 asp.net 身份的情况下对 Web API 进行身份验证?

我在同一个解决方案中有一个 MVC 和一个 Web API 项目,在 MVC 项目上,我有一个很小的管理区域,受登录名和密码保护(仅适用于一个用户)。在这个区域,我使用 API 调用获取 clinet 端的数据。

这是我的登录功能:

public ActionResult SubmitLogin(string UserName, string Password)
    {
        if (ModelState.IsValid)
        {
            if (UserName == "xxxxx" && Password == "yyyyy")
            {
                FormsAuthentication.SetAuthCookie(UserName, true);
                return RedirectToAction("Index", @"Admin/Users");
            }
        }
        var errors = (from value in ModelState.Values
                      from error in value.Errors
                      select error.ErrorMessage).ToList();

        if (errors.Count == 0)
        {
            errors.Add("UserName or Password are incorrect");
        }

        ViewBag.Message = errors;
        return View("Index");
    }

登录表单工作正常,我的问题在于 API 调用,我的 API 控制器是 [Authorize] 但是当我发出请求时:

self.getUsers = function (callback) {
    $.get("../MySite.API/Users/GetUsers/", callback);
}

我收到 401 错误。

我知道我必须以某种方式发送AuthCookie,但我不确定如何发送。

任何帮助将不胜感激。

【问题讨论】:

    标签: c# asp.net-mvc authentication asp.net-web-api asp.net-mvc-5


    【解决方案1】:

    您可以制作自己的AuthorizationFilterActionFilter 以在执行操作之前检查用户的身份验证和授权。

    这只是一个如何使用ActionFilter 完成的示例。您可以根据需要自行设计:

    public class CanEditReport : ActionFilterAttribute  
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var reportID = Convert.ToInt32(filterContext.ActionParameters["id"]);
            var report = ReportsManager.GetByID(reportID);
            int userID = 0;
            bool hasID = int.TryParse(filterContext.HttpContext.Session["CurrentUserID"].ToString(), out userID);
            if (!hasID)
            {
                filterContext.Controller.TempData["FlashMessage"] = "Please select a valid User to access their reports.";
                //Change the Result to point back to Home/Index
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "Index" }));
            }
            else //We have selected a valid user
            {
                if(report.UserID != userID)
                {
                    filterContext.Controller.TempData["FlashMessage"] = "You cannot view Reports you have not created.";
                    //Change the Result to point back to Home/Index
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "Index" }));
                }
            }
            base.OnActionExecuting(filterContext);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-16
      • 2017-07-30
      • 2016-12-22
      • 1970-01-01
      • 2015-09-17
      • 1970-01-01
      • 2013-10-05
      • 2014-06-02
      • 2017-09-28
      相关资源
      最近更新 更多