9

I am implementing refreshToken in my ASP.NET CORE WEB API + React application and I can't figure out how to send this token back to my API with another request.

My API adds refreshToken as HttpOnly cookie to requests.

  1. Api endpoint
        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> GenerateToken([FromForm]LoginModel model)
        {
            var result = await _userService.GetTokenAsync(model);
            SetRefreshTokenInCookie(result.RefreshToken);
            return Ok(result);
        }
  1. Adding refresh token to response
        private void SetRefreshTokenInCookie(string refreshToken)
        {
            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Expires = DateTime.UtcNow.AddDays(10)
            };
            Response.Cookies.Append("refreshToken", refreshToken, cookieOptions);
        }

I can see cookie with refreshToken while browsing 'Network' in my chrome dev tools. enter image description here

But there is no cookie in 'Application'

enter image description here

And there is no cookie in next request as well.

enter image description here

I am using Axios to send requests. How can I get that refreshToken in my backend?

5
  • you want to check if there is a cookie for every req you send? Commented Oct 27, 2020 at 19:39
  • I want to check only when token will expire and server return 401. I already have this in my code, but I cant send httponly cookie with axios. Commented Oct 28, 2020 at 7:49
  • 1
    axios.get('some api url', {withCredentials: true}); try using withcredentials Commented Oct 28, 2020 at 8:25
  • Already tried this. Doesn't work. Cookie should automatically be visible in 'Application' tab in dev tools, right? With httponly flag checked Commented Oct 28, 2020 at 8:31
  • Very annoying problem. I fixed it. It is about CookieOptions. Here is the solution Commented Jul 4, 2021 at 4:03

3 Answers 3

11

You need to add withCredentials. With this flag, it will send to the server all HttpOnly cookies.

axios("http://example.com/api/things/", {
  method: "post",
  data: someJsonData,
  withCredentials: true
})
Sign up to request clarification or add additional context in comments.

Comments

2

It turns out that was CORS issue. Setting this in my Startup.cs file worked like a charm.

            services.AddCors(options =>
            {
                options.AddPolicy("CORSAllowLocalHost3000",
                  builder =>
                  builder.WithOrigins("http://localhost:3000")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials() // <<< this is required for cookies to be set on the client - sets the 'Access-Control-Allow-Credentials' to true
                 );
            });

2 Comments

What if you get a console error stating that you cannot specify .AllowAnyOrigin() and .AllowCredentials() at the same time. It states to use credentials you need to provide the origins which we do not have since some origins are not web clients
@mjwrazor I know this answer is probably 2 years late but if anyone else stubmles accross it: You cannot use AnyOrigin and AllowCredentials at the same time. This is due to security implications. Just specify the origin Address like the post you commented, "WithOrigins(".....")"
2

In my case, the API and UI had different URLs and I had to add two additional settings to CookieOptions:

private void SetRefreshTokenCookie(string token)
{
    var cookieOptions = new CookieOptions
    {
        HttpOnly = true,
        Expires = DateTime.UtcNow.AddDays(1),
        SameSite=SameSiteMode.None,
        Secure=true
    };
    Response.Cookies.Append("refreshToken", token, cookieOptions);
}

SameSiteMode.None inform that cookie is set by respons from different origin. This option indicates that you need Secure=true. This opions means that

A cookie with the Secure attribute is only sent to the server with an encrypted request over the HTTPS protocol.

like was described here: developer.mozilla.org

After that changes, you will have set a cookie in the browser in the Application tab

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.