我有一个Angular 6+应用程序,配置为使用Angular Universal利用服务器端渲染。 我还使用TransferState来避免服务器和客户端应用程序上的重复API调用。
我的角应用程序中的身份验证基于令牌。
问题是用户第一次打开我的Web应用程序,这导致为未经过身份验证的用户呈现index.html,而用户实际登录但没有机会将令牌转移到服务器。因此,当客户端应用程序swapped与服务器应用程序时,由于浏览器的localStorage / sessionStorage中存在令牌,因此需要再次调用API。
我使用node.js和express.js来实现服务器端呈现。
我认为解决方案是使用会话和cookie。这需要我很多工作,因为我不熟悉node.js来处理会话/ cookie。有没有快速简便的解决方案?
对于面临同样问题的其他人,这是解决方案。
client-app应该在浏览器cookie中保存服务器端呈现所需的状态数据(例如,身份验证信息)。浏览器将自动在第一个请求的标头中发送cookie以获取index.html
。然后在server.js
中我们应该从请求标头中提取cookie并使用extraProviders
的renderModuleFactory
将其传递给服务器应用程序。
我们首先需要的是处理浏览器cookie的服务。我宣布一个灵感来自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;
}
}
接下来,我们在浏览器的cookie中保存数据(我们想要传递给服务器应用程序)
@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));
}
}
最后在server.ts
中提取令牌并将其传递给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);
});
});
并在这样的服务中使用提供的cookie:
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;
}
}
在app.server.module.ts
的提供者使用ServerStorage
中的StubBrowser
providers: [
{provide: BROWSER, useClass: StubBrowser, deps: [ServerStorage]},
]
@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 = '';
}