简体   繁体   English

Web API身份验证(无asp.net身份)

[英]Web API Authentication (without asp.net identity)

Is it possible to authenticate a Web API without using asp.net identity? 是否可以在不使用asp.net身份的情况下验证Web API?

I have a MVC and a Web API project within the same solution, on the MVC project I have a very small Admin area protected with a login and password (just for one user). 我在同一个解决方案中有一个MVC和一个Web API项目,在MVC项目上,我有一个很小的管理区域,该区域受登录名和密码保护(仅适用于一个用户)。 On this area I get the data on clinet side using API calls. 在这个区域,我使用API​​调用在clinet端获取数据。

This is my Login function: 这是我的登录功能:

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

The Login form work fine, my issue is with the API calls, my API controller is [Authorize] but when I make a request: 登录表单工作正常,我的问题是API调用,我的API控制器是[Authorize]但是当我发出请求时:

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

I get a 401 error. 我收到401错误。

I understand I have to somehow send the AuthCookie but I'm not sure how. 我知道我必须以某种方式发送AuthCookie但不确定如何发送。

Any help would be appreciated. 任何帮助,将不胜感激。

You can make your own AuthorizationFilter or ActionFilter to check the user's authentication and authorization before the action is executed. 您可以创建自己的AuthorizationFilterActionFilter以在执行操作之前检查用户的身份验证和授权。

This is just a sample how it can be done with ActionFilter . 这只是使用ActionFilter可以完成的示例。 You can design your own as required: 您可以根据需要设计自己的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM