HttpOnly cookies are not attached to request. | .NET API and Angular

Discussão em 'Angular' iniciado por Mateusz Sawosz, Outubro 22, 2024.

  1. I have .NET Api running on https://localhost:1908/ and Angular app running on https://localhost:4200/ (ng serve --ssl)
    I am trying to retrieve in my .NET API the HttpOnly cookie stored in the browser, but unfortunately I can't.

    In my API, I have the following CORS configuration

    services.AddCors(options =>
    {
    options.AddPolicy("cors",
    builder => builder.WithOrigins("https://localhost:4200")
    .AllowAnyMethod()
    .AllowCredentials()
    .AllowAnyHeader());
    });


    In requeset under the /sign-in endpoint, I include the refresh token as an HttpOnly cookie.

    HttpContext.Response.Cookies.Append("refreshToken", tokens.RefreshToken.Token, new CookieOptions
    {
    Expires = DateTimeOffset.FromUnixTimeMilliseconds(tokens.RefreshToken.Expiry),
    HttpOnly = true,
    IsEssential = true,
    Secure = false, // I also tried with this setting to true
    SameSite = SameSiteMode.None
    });


    and this cookie i visible from browser [screenshot here]

    Im trying to get this refresh token back from angular in /refresh endpoint.

    refreshTokens() {
    return this.httpClient.post(
    environment.apiUrl + '/refresh',
    {},
    { observe: 'response', withCredentials: true }
    );
    }


    But the cookie is missing from the request headers. Also I am not getting this cookie in my Api controller

    [HttpPost("refresh")]
    [SwaggerOperation("Refresh")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> RefreshToken()
    {
    var accessToken = Request.Headers.Authorization.ToString()["Bearer ".Length..].Trim();
    var refreshToken = Request.Cookies["refreshToken"];

    var command = new RefreshRequest(accessToken, refreshToken);
    await _mediator.Send(command);

    var tokens = _authTokenStorage.GetTokens(command.Id);

    HttpContext.Response.Cookies.Append("refreshToken", tokens.RefreshToken.Token, new CookieOptions
    {
    Expires = DateTimeOffset.FromUnixTimeMilliseconds(tokens.RefreshToken.Expiry),
    HttpOnly = true,
    IsEssential = true,
    Secure = false,
    SameSite = SameSiteMode.None
    });

    return Ok(new { tokens.AccessToken.Token });
    }

    Continue reading...

Compartilhe esta Página