Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

send token to server in angular universal

I have an Angular 6+ app which is configured to utilize server side rendering using Angular Universal.
I also used TransferState to avoid duplicate API calls on the server and client app.

Authentication in my angular app is based on token.

The problem is in the first time the user opens my web app, which results to rendering index.html for a user which is not authenticated whereas the user actually is logged in but there is no opportunity to transfer the token to the server. So, when the client app swapped with server app, it is required to call APIs again because of the existance of token in the browser's localStorage/sessionStorage.

I used node.js and express.js to implement server side rendering.

I think the solution is to use session and cookies. This requires a lot of work for me since I'm not familiar with node.js to handle sessions/cookies. Is there any fast and easy solution?

like image 335
Fartab Avatar asked Sep 01 '18 10:09

Fartab


1 Answers

For others facing the same problem, here is the solution.

client-app should save the state data required for server side rendering (e.g. authentication info) in the browser cookies. Browser will automatically sends cookies in header of the first request to fetch index.html. Then in the server.js we should extract cookie from request header and pass it to server-app using extraProviders of renderModuleFactory.

First thing we need is a service to deal with browser cookies. I declared one inspired from this post (github repo link)

import {Injectable} from '@angular/core';

@Injectable()
export class CookieManager {

    getItem(cookies, sKey): string {
        if (!sKey) {
            return null;
        }
        return decodeURIComponent(cookies.replace(new RegExp(
            '(?:(?:^|.*;)\\s*' +
            encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, '\\$&') +
            '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1'
            )
        ) || null;
    }

    setItem(cookies, sKey, sValue, vEnd?, sPath?, sDomain?, bSecure?): string {
        if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
            return cookies;
        }
        let sExpires = '';
        if (vEnd) {
            switch (vEnd.constructor) {
                case Number:
                    sExpires = vEnd === Infinity ? '; expires=Fri, 31 Dec 9999 23:59:59 GMT' : '; max-age=' + vEnd;
                    break;
                case String:
                    sExpires = '; expires=' + vEnd;
                    break;
                case Date:
                    sExpires = '; expires=' + vEnd.toUTCString();
                    break;
            }
        }
        return encodeURIComponent(sKey) + '=' + encodeURIComponent(sValue) + sExpires +
            (sDomain ? '; domain=' + sDomain : '') + (sPath ? '; path=' + sPath : '') + (bSecure ? '; secure' : '');
    }

    removeItem(cookies, sKey, sPath?, sDomain?): string {
        if (!this.hasItem(cookies, sKey)) {
            return cookies;
        }
        return encodeURIComponent(sKey) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' +
            (sDomain ? '; domain=' + sDomain : '') + (sPath ? '; path=' + sPath : '');
    }

    hasItem(cookies, sKey): boolean {
        if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) {
            return false;
        }
        return (new RegExp('(?:^|;\\s*)' +
            encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\='
        )).test(cookies);
    }

    keys(cookies) {
        const aKeys = cookies.replace(
            /((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, ''
        ).split(/\s*(?:\=[^;]*)?;\s*/);
        for (let nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) {
            aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]);
        }
        return aKeys;
    }
}

Next we save data (which we want to pass to the server-app) in cookie of browser

@Injectable()
export class AuthenticationService {
    constructor(private http: HttpClient, 
                private cookieManager: CookieManager, 
                @Inject(BROWSER) private browser: BrowserInterface) { }

    login(username: string, password: string) {
        return this.http.post<any>(`${apiUrl}/users/authenticate`, { username: username, password: password })
            .pipe(tap(user => {
                if (user && user.token) {
                    // store authentication details in local storage and browser cookie
                    this.browser.document.localStorage.setItem('authenticatedUser', JSON.stringify(user));
                    this.saveInCookies('authenticatedUser', user)
                }
            }));
    }

    private saveInCookies(key, data){
        const document = this.browser.document;
        let cookieStorage = this.cookieManager.getItem(document.cookie, 'storage');
        cookieStorage = cookieStorage ? JSON.parse(cookieStorage) : {};
        cookieStorage[key] = data;
        document.cookie = this.cookieManager.setItem(document.cookie, 'storage', JSON.stringify(cookieStorage));
    }
}

Finally in server.ts extract token and pass it to server-app:

app.engine('html', (_, options, callback) => {
    // extract request cookie    
    const cookieHeader = options.req.headers.cookie;
    renderModuleFactory(AppServerModuleNgFactory, {
        document: template,
        url: options.req.url,
        extraProviders: [
            provideModuleMap(LAZY_MODULE_MAP),
            // pass cookie using dependency injection
            {provide: 'CLIENT_COOKIES', useValue: cookieHeader}  
        ]
    }).then(html => {
        callback(null, html);
    });
});

and use the provided cookie in a service like this:

import {Inject} from '@angular/core';

export class ServerStorage {

    private clientCookies: object;

    constructor(@Inject('CLIENT_COOKIES') clientCookies: string,
                cookieManager: CookieManager) {
        const cookieStorage = cookieManager.getItem(clientCookies, 'storage');
        this.clientCookies = cookieStorage ? JSON.parse(cookieStorage) : {};
    }

    clear(): void {
        this.clientCookies = {};
    }

    getItem(key: string): string | null {
        return this.clientCookies[key];
    }

    setItem(key: string, value: string): void {
        this.clientCookies[key] = value;
    }
}

In the providers of app.server.module.ts use the ServerStorage in the StubBrowser

providers: [
    {provide: BROWSER, useClass: StubBrowser, deps: [ServerStorage]},
]



Here is the stub browser, window and document I used:
@Injectable()
export class StubBrowser implements BrowserInterface {

    public readonly window;

    constructor(localStorage: ServerStorage) {
        this.window = new StubWindow(localStorage);
    }


    get document() {
        return this.window.document;
    }

    get navigator() {
        return this.window.navigator;
    }

    get localStorage() {
        return this.window.localStorage;
    }
}

class StubWindow {
    constructor(public localStorage: ServerStorage) {
    }

    readonly document = new StubDocument();
    readonly navigator = {userAgent: 'stub_user_agent'};
}

class StubDocument {
    public cookie = '';
}
like image 109
Fartab Avatar answered Nov 04 '22 13:11

Fartab