How to set httpOnly flag in ngCookies?

rublex picture rublex · May 10, 2015 · Viewed 8.4k times · Source

I have a JWT token that I'd like to store in a cookie. The cookie needs to have at least HttpOnly flag set, but I would also want to set the Secure flag to true.

From the angular docs I know I can store my token in cookies like this:

// using 'ngCookies'

createToken(jwt_token) {
    $cookies.put('jwt', jwt_token);
},
retrieveToken() {
    return $cookies.get('jwt');
}

But it's not clear how I can specify the HttpOnly and Secure flags. The docs say it has an options field for put() and get(), but then it mentions $cookiesProvider. I'm not sure how that fits in, or where it should be declared, or if it needs to be set every time I do a put() or get()?

So would it be something like:

createToken(jwt_token) {
    $cookiesProvider['domain'] = 'www.mydomain.com';
    $cookiesProvider['secure'] = true;
    $cookies.put('jwt', jwt_token);
},
retrieveToken() {
    $cookiesProvider['domain'] = 'www.mydomain.com';
    $cookiesProvider['secure'] = true;
    return $cookies.get('jwt');
}

Or is that completely wrong? I didn't see any HttpOnly flag either, but I do see domain which I set to www.mydomain.com. Is that equivalent to HttpOnly = true?

Answer

Ayoub Kaanich picture Ayoub Kaanich · Jul 20, 2015

You can't do this using ngCookies. A HttpOnly cookie can't be created from JavaScript, the alternative however, is to make an ajax query to the server that will add a Set-Cookie HTTP response.

Related: Set a cookie to HttpOnly via Javascript