Base solution for your next web application
Open Closed

Cookie Not Sent via Generated Service Proxy #12421


User avatar
0
ips-jm created

Hi,

we are setting a frontend cookie like this:

selectWorkplace(workplace: WorkplaceDto): void { this.selectedWorkplace = workplace; abp.utils.setCookieValue('selectedWorkplaceId', workplace.id.toString()); }

Our goal is for this cookie to be sent with requests via the generated service proxy, so that we can access it in the backend like this:

private async Task<Workplace> GetWorkplaceFromRequest()
{
    var workplaceId = httpContextAccessor.HttpContext?.Request.Cookies["selectedWorkplaceId"];
    if (string.IsNullOrEmpty(workplaceId))
    {
    throw new UserFriendlyException("No workplace selected. Please select a workplace in the header.");
    }


    var workplace = await repo(w => w.Id == long.Parse(workplaceId));
    if (workplace == null)
    {
        throw new UserFriendlyException($"Workplace with ID {workplaceId} not found.");
    }

    return workplace;
}

However, the cookie does not seem to be included in requests made via the generated service proxy. Is there a specific configuration required to ensure the cookie is sent with the request?

Thanks in advance!

Markdown is supported
Copy & paste or drag & drop images (max 30 MB per image)

2 Answer(s)
  • User Avatar
    0
    oguzhanagir created
    Support Team

    Hi @ips-jm

    You need to make some changes when sending backend application cookies from the Angular client. First, you need to add specific attributes for cross-origin when setting cookies. You also need to make changes in the NSwag configuration.

    abp.utils.setCookieValue('selectedWorkplaceId', workplace.id.toString(), undefined, abp.appPath, undefined, { sameSite: 'None', secure: true });
    

    You can define it this way when setting a cookie. The first undefined is where you specify the duration for which the cookie will remain. The second undefined is where you specify the domain of your application (you can leave it undefined for localhost). For cross-origin to work, the sameSite attribute must be set to None and the secure attribute must be true.

    You also need to set the withCredentials value to true in the "service.config.nswag" file located under the nswag folder.

    "angular>nswag>service.config.nswag"

    "codeGenerators": {
        "openApiToTypeScriptClient": {
          //..
          "withCredentials": true,
        }
    }
    
    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)
  • User Avatar
    0
    ips-jm created

    Thank you!

    Markdown is supported
    Copy & paste or drag & drop images (max 30 MB per image)