Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set secure flag in my cookie using ngx-cookie-service for Angular?

I want to set the secure flag in my cookie when I create it. I think I have the solution but I want to be sure in order to continue. I use the ngx-cookie-service to set my cookie.

Here is my code:

const now = new Date();
now.setHours(now.getHours() + 8);
const secureFlag = true;
this.cookieService.set('usertype', 'agent', now, '/', '/', secureFlag);

The thing is that I don't know if I have to declare the 4th and 5th parameter like that because if I don't declare them it shows error.

For example I try this:

const now = new Date();
now.setHours(now.getHours() + 8);
const secureFlag = true;
this.cookieService.set('usertype', 'agent', now, secureFlag);

and it warns me with Argument of type 'true' is not assignable to parameter of type 'string'

Do I have to use '/' for path and domain parameters when I don't want to define them?

like image 207
TheodoreTsg Avatar asked Sep 11 '19 09:09

TheodoreTsg


People also ask

How do you set a cookie with a secure flag?

Launch Google Chrome and go to either WEB or CAWEB portal website. Press F12 (from Keyboard) to launch Developer Tools. Go to Application tab -> Cookies ( left Panel) and ensure the Secure column was ticked.


2 Answers

This will work, also to do testing disable SameSite by default cookies on Google Chrome if you are having problems with Google Chrome.

Paste this into your browser and it will take you to the SameSite settings and disable.

chrome://flags/#same-site-by-default-cookies

this.cookieService.set('sessionuser', username, 1 , '/', 'localhost', false, "Lax" );
like image 99
Gabriel Sanchez Avatar answered Oct 20 '22 15:10

Gabriel Sanchez


The get method of CookieService supports the following parameters:

    /**
     * @param name     Cookie name
     * @param value    Cookie value
     * @param expires  Number of days until the cookies expires or an actual `Date`
     * @param path     Cookie path
     * @param domain   Cookie domain
     * @param secure   Secure flag
     * @param sameSite OWASP samesite token `Lax`, `None`, or `Strict`. Defaults to `None`
     */
    set(name: string, value: string, expires?: number | Date, path?: string, domain?: string, secure?: boolean, sameSite?: 'Lax' | 'None' | 'Strict'): void;

The error Argument of type 'true' is not assignable to parameter of type 'string' it’s because you’re sending the secure parameter instead of path.

like image 26
edu Avatar answered Oct 20 '22 13:10

edu