简体   繁体   中英

Web API Authentication (without asp.net identity)

Is it possible to authenticate a Web API without using asp.net identity?

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). On this area I get the data on clinet side using API calls.

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:

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

I get a 401 error.

I understand I have to somehow send the AuthCookie but I'm not sure how.

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.

This is just a sample how it can be done with 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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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