locked
Check if cookie is persistent then save it back RRS feed

  • Question

  • User1501362304 posted

    Hi,

    I am using .Net Core MVC and .Net Core WEB API (both 3.1). In MVC application I am calling API using http client. 
    API is returning a jwt access token and refresh token on authentication which I am storing in cookie so that it can be sent to other endpoints automatically.

    Based on the user's selection on login form (Remember me checkbox) I am saving this cookie as persistent or session. 
    Now when mvc application calls authorized endpoint and token is valid then it is fine else API returns 401 which I handle using http message handler in mvc application, I try to regenerate token and hit the API again with new token which I save again in cookies. So far so good, but I don;t know how to check if cookie was persistent or session based, because when I am reading it to generate new access token then I should store it back as per user's selection on login form. Currently irrespective of user's selection cookies are being saved as session on regeneration.

    Below is code sample.

    Register Http client and message handler in MVC

    services.AddHttpClient<IAPIService>("API Service", options =>
                {
                    options.BaseAddress = new Uri(Configuration.GetValue<string>("ApiUrl"));
                    options.Timeout = TimeSpan.FromMilliseconds(15000);
                    options.DefaultRequestHeaders.Accept.Clear();
                    options.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    options.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
                })
                .AddTypedClient(client => RestService.For<IAPIService>(client))
                .AddHttpMessageHandler<AuthorizationMessageHandler>();

    Message handler is as below

    public class AuthorizationMessageHandler : DelegatingHandler
    {
            private readonly IHttpContextAccessor httpContextAccessor;
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancelToken) { HttpRequestHeaders headers = request.Headers; AuthenticationHeaderValue authHeader = headers.Authorization; if (authHeader != null) { string jwToken = Convert.ToString(httpContextAccessor.HttpContext.Request.Cookies["AccessToken"]); headers.Authorization = new AuthenticationHeaderValue(authHeader.Scheme, jwToken); } var response = await base.SendAsync(request, cancelToken); if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized ) { var result = await RefreshToken(); if (result != null) { string jwToken = result; headers.Authorization = new AuthenticationHeaderValue(authHeader.Scheme, jwToken); response = await base.SendAsync(request, cancelToken); } } protected async Task<string> RefreshToken() { string accessToken = Convert.ToString(httpContextAccessor.HttpContext.Request.Cookies["AccessToken"]); string refreshToken = Convert.ToString(httpContextAccessor.HttpContext.Request.Cookies["RefreshToken"]); UserLoginToken model = new UserLoginToken { AccessToken = accessToken, RefreshToken = refreshToken }; var result = await _APIService.RegenerateTokenAsync(model); if (result.Succeeded) { CookieOptions cookieOptions = new CookieOptions { IsEssential = true, HttpOnly = true, SameSite = SameSiteMode.Strict }; // Here I want to Set expiration time of cookies based on remember me setting by user at time of login httpContextAccessor.HttpContext.Response.Cookies.Append("AccessToken", result.Data.AccessToken, cookieOptions); httpContextAccessor.HttpContext.Response.Cookies.Append("RefreshToken", result.Data.RefreshToken, cookieOptions); return result.Data.AccessToken; } return null; } }

    In above code snippet when setting cookie options, I want to set Expires property based on user's remember me property but not sure how to check and set in above code. Would I need to save another cookie to store user's remember me setting or there is any better solution?

    Thanks

    Sunday, February 28, 2021 6:10 PM

All replies

  • User-474980206 posted

    The browser only sends the cookie. It does nor send expiration, httpsonly or persistence. If you want this info, you need to add to the cookie data.

    Monday, March 1, 2021 12:51 AM