Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Action doesn't create a cookie when its called by external API

Let's say we have code as follows:

public class HomeController : Controller
{
    [HttpPost]
    public IActionResult AdvanceTokenCallback(string apiToken)
    {
        Response.Cookies.Append("Token", apiToken, new Microsoft.AspNetCore.Http.CookieOptions()
        {
            Path = "/",
            Expires = _tokenCookieExpirationTime
        });
        return RedirectToAction(nameof(CreateWorkItem));
    }

    [HttpGet]
    public IActionResult CreateWorkItem()
    {
        string token = Request.Cookies["Token"];
        return View();
    }
}

When the action AdvanceTokenCallback is called from external API the token variable in the CreateWorkItem action becomes a null. However in a case when I create a "bridge" action and move the logic which creates the cookie there, then the token located in CreateWorkItem contains a value which is something that I expected.

public class HomeController : Controller
{
    [HttpPost]
    public IActionResult AdvanceTokenCallback(string apiToken)
    {
        return RedirectToAction(nameof(BridgeRedirect), new { apiToken });
    }

    [HttpGet]
    public IActionResult BridgeRedirect(string apiToken)
    {
        Response.Cookies.Append("Token", apiToken, new Microsoft.AspNetCore.Http.CookieOptions()
        {
            Path = "/",
            Expires = _tokenCookieExpirationTime
        });
        return RedirectToAction(nameof(CreateWorkItem));
    }

    [HttpGet]
    public IActionResult CreateWorkItem()
    {
        string token = Request.Cookies["Token"];
        return View();
    }
}

Any idea why does it happen and is there a possibility to avoid having this extra BridgeRedirect action with extra redirect?

like image 323
GoldenAge Avatar asked Jan 29 '19 17:01

GoldenAge


1 Answers

I found that code works and do not on different machines and different environments when I run the app on localhost. After I set the IsEssential attribute to true when creating the Cookie everything works fine. From the Microsoft documentation:

IsEssential - Indicates if this cookie is essential for the application to function correctly. If true then consent policy checks may be bypassed. The default value is false.

So the solution in my case is to just create a cookie like this:

Response.Cookies.Append("Token", apiToken, new Microsoft.AspNetCore.Http.CookieOptions()
{
    IsEssential = true,
    Expires = _tokenCookieExpirationTime
});

Using this way I don't need having this extra BridgeRedirect anymore.

like image 61
GoldenAge Avatar answered Sep 21 '22 15:09

GoldenAge