Access to user data in WebAPI from context / cookie

Update:

I changed my code to FormsAuthentication.SetAuthCookie(_model.UserName, true);. I have 2 Web.config files, 1 for MVC and another for WebAPI. In the MVC configuration, I define

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

Both applications are in the same domain.


Update: Should we use cookies in the WebAPI?


I currently have an MVC project that uses forms authentication and a WebAPI project. The problem is that I cannot get the user associated with the request in the WebAPI project. I thought it would be possible or maybe the implementation is wrong?

NB: I put the cookie in the WebAPI controller method as a test, but not where it should be.

MVC - processes an entry request, creates an auth ticket.

// POST: /Account/Login
[AllowAnonymous]
[HttpPost]
public ActionResult Login(LoginModel _model, string _returnUrl)
{
    if (ModelState.IsValid)
    {
        if (Membership.ValidateUser(_model.UserName, _model.Password))
        {
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(_model.UserName, true, 15);
            string encryptedTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            Response.Cookies.Add(cookie);

            // set redirect
        }
    }

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

WebAPI - processes update request

[AcceptVerbs("PUT")]
public HttpResponseMessage UpdateInfo(int _id, ExampleModel _model)
{
    try
    {
        HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

        if (authCookie != null)
        {
            string encTicket = authCookie.Value;

            if (!String.IsNullOrEmpty(encTicket))
            {
                // decrypt the ticket if possible.
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(encTicket);

                var userData = ticket.UserData;
            }
        }

        // do update
        return Request.CreateResponse(HttpStatusCode.OK, data, GlobalConfiguration.Configuration);
    }
    catch (Exception err)
    {
        m_logger.Error(err);
        throw;
    }
}
+5
2

? ?

if (Membership.ValidateUser(_model.UserName, _model.Password))
{
    FormsAuthentication.SetAuthCookie(_model.UserName, true);

    // set redirect
}

, web.config:

<authentication mode="Forms">
    <forms timeout="15" />
</authentication>

, cookie, . User.Identity.Name. MVC Controller, ApiController s.

, MVC WebAPI - ( ), MVC WebAPI machineKey web.config . , web.config, machineKey (decryption, decryptionKey, validation validationKey). , , cookie.ASPXAUTH.

cookie WebAPI?

, cookie, , /. HTTP, , , .. WebAPI - . , . , .

, , :

HttpCookie authCookie = HttpContext.Current.Request.Cookies["name"];

cookie ApiController, :

IEnumerable<CookieHeaderValue> cookies = this.Request.Headers.GetCookies("name");
if (cookies.Any())
{
    IEnumerable<CookieState> cookie = cookies.First().Cookie;
    if (cookie.Any())
    {
        string value = cookie.First().Value;
    }
}

: http://aspnetresources.com/tools/machineKey

" ", <machineKey ../> - <system.web> web.config.

, web.config, . , , , , .

, , , . validationKey encryptionKey appSettings, appSettings ( - CloudConfigCrypto). , -, . Microsoft.Web.Administration.ServerManager machineKey , Application_Start. , , .

- , web.config .

+9

-API MVC WebSecurity WebMatrix.WebData namespace. , , , reset . cookie .

, , -API MVC.

API

:

if(WebSecurity.Login(username, password))
{
    return Request.CreateErrorResponse(
        HttpStatusCode.Forbidden, "Invalid credentials");
}
else
{
    return Request.CreateResponse(HttpStatusCode.OK);
}

:

if(WebSecurity.UserExists(username))
{
    return Request.CreateErrorResponse(
        HttpStatusCode.BadRequest, "Username already exists");
}

WebSecurity.CreateUserAndAccount(username, password, data);

HttpResponseMessage response = Request.CreateResponse(
    HttpStatusCode.Created, yourUserObject);
    response.Headers.Location = new Uri(
        Url.Link("DefaultApi",
            new { controller = "users", id = WebSecurity.GetUserId(username) }));
return response;

MVC.

0

All Articles