ngx encrypt cookie


    Thank you checking my  blog. I got some really cool feature library that makes our development more easy. In general we use cookies to store token value / email / or any thing that we require to perform on our web application. we also keep expire date when will or till the date cookie will live , if the expire date arrives it will remove the value automatically cool right but some times we not use cookies because user can manipulate the cookie value or its possible to change cookie values. it happens because the cookie value is human readable. so here i brought an solution to this so we can store cookies but it will not be a human readable string.so lets see "How to store encrypted value in cookies or How to encrypt a value to store in cookies"
                                    
                                                The library we are going to use will work in Type script supported language only. here i am using Angular. now discuss what this library will do . it will take the cookie name, value and automatically set cookie with encrypted value (we have to pass argument true or false) to encrypt or not. There are lot more things we can do with this. we can also pass the `path` where we want to store our cookie eg: ("/","coder-adda.blogspot.com") . we can get all cookie stored in the path or domain . same way we can delete each cookie or all cookies at a time.

                    let start coding...
     create angular project with this command
ng new app

    install the package with below command 
  


            
npm i ngx-encrypt-cookie --save
or
yarn add ngx-encrypt-cookie
Import the cookie service from library into component or app.module.ts or custom module. here i am importing inside app.component.ts

....
import {NgxEncryptCookieService} from 'ngx-encrypt-cookie'

@Component({
  ......
  providers: [NgxEncryptCookieService]
}) export class AppComponent {
     Don't forget to inject service into component or module.ts files because there may be no issue in development mode but it prod  Null Injection error will raise. every service we use in library should inject into app.

next create instance for service we imported.

constructor(
    private cookie:NgxEncryptCookieService,
){}


     now let start our main coding with this library. these are all prerequisites to use a library in our application.

 library has a generateKey() function to generate a secret key. with this key we will encrypt and decrypt the cookie value.

Note : The key should be same for both encryption  and 
decryption. Beware that is case sensitive.

lets generate our secret key.

var key = this.cookie.generateKey();
 lets store a cookie with name coder-adda but before that lets have a look at that function  which  is used to store cookie.

set( name: string, value: string, encrypt:boolean, key?:string, expires?: number | Date, path?: string, domain?: string, secure?: boolean, sameSite?: 'Lax' | 'Strict' | 'None' ): void;

  • Sets a cookie with the specified name and value.pass true or false to either encrypt values or not. It is good practice to specify a path. If you are unsure about the path value, use '/'. If no path or domain is explicitly defined, the current location is assumed. sameSite defaults to Lax.
this.cookie.set("coder-adda","testvalue",true,"my secret key");

now  lets use our own secret key which is nothing but a string either generate random characters  or use human-readable string.
this.cookie.set("customKey","something",true,"my secret key");
console image:


now let print the cookie value 

without decryption:

this.cookie.get("customKey",false);
console image:

with decryption :

this.cookie.get("customKey",true,"my secret key");

console image:


getAll(encryption?:boolean,key?:string): { [key: string]: string }


const cookies = this.cookie.getAll(true,key);  // use if you have one encrypted value

const normalCookies = this.cookie.getAll()    // use this if you have zero encrypted value


#f03c15 NOTE:

  • For security reasons, it is not possible to define cookies for other domains. Browsers do not allow this. Read this and this StackOverflow answer for a more in-depth explanation.

  • Browsers do not accept cookies flagged the same site = 'None' if the secure flag isn't set as well. NgxSecureCookies will override the secure flag to true if sameSite='None'.



delete( name: string, path?: string, domain?: string, secure?: boolean, sameSite: 'Lax' | 'None' | 'Strict' = 'Lax' ): void;


this.cookie.delete('test');

  • Deletes a cookie with the specified name. It is best practice to always define a path. If you are unsure about the path value, use '/'.

#f03c15 Important:

  • For security reasons, it is not possible to delete cookies for other domains. Browsers do not allow this. Read this and this StackOverflow answer for a more in-depth explanation.

deleteAll( path?: string, domain?: string, secure?: boolean, sameSite: 'Lax' | 'None' | 'Strict' = 'Lax' ): void;


this.cookie.deleteAll("/");

  • Deletes all cookies that can access. It is always a best practice to define a path to delete. If you are not sure about the path where the cookie store pass '/'.
  

Comments

Popular posts from this blog

Alias