zookeeper节点加密_用角度通用和节点js加密cookie

zookeeper节点加密

Cookies are a ubiquitous feature of web applications, as anyone clicking GDPR notifications for the last several months has realized. Securely handling the data in those cookies is just as much a requirement as the consent notification. Encrypting your Angular and Node.js application cookies is a way to prevent unauthorized access to confidential and personal information, and it’s easy to implement.

Cookies是Web应用程序无处不在的功能,因为过去几个月中单击GDPR通知的任何人都已经意识到。 安全地处理这些cookie中的数据与同意通知一样重要。 加密Angular和Node.js应用程序cookie是一种防止未经授权访问机密和个人信息的方法,并且易于实现。

As you know, using an httpOnly cookie helps prevent cross-site scripting (XSS) attacks. (You can learn more in another post.) But what about protecting one registered user’s data against another registered user? Are cookies vulnerable to attacks from trusted users?

如您所知,使用httpOnly cookie有助于防止跨站点脚本 (XSS)攻击。 (您可以在另一篇文章中了解更多信息。)但是,如何保护一个注册用户的数据免受另一个注册用户的侵害呢? Cookies是否容易受到来自受信任用户的攻击?

This post will demonstrate how authenticated users can get unauthorized access to other users’ cookie data. It will also show you how to encrypt your cookies so the data can only be read by your code, not by users.

这篇文章将演示经过身份验证的用户如何能够未经授权访问其他用户的cookie数据。 它还将向您展示如何加密cookie,以便只能由您的代码而非用户读取数据。

The code in this post uses the cryptography library in OpenSSL to perform the encryption and decryption, but it doesn’t require you to know much about the library or cryptography to use it. You also won’t need to perform a complicated install or build process to use cryptography. (Big sigh of relief here, right?)

这篇文章中的代码使用OpenSSL中的加密库来执行加密和解密,但是使用它不需要您对库或加密有很多了解。 您也不需要执行复杂的安装或构建过程即可使用加密。 (在这里大松一口气,对吗?)

使用Angular Universal和Node.js加密Cookie的前提条件 (Prerequisites for encrypting cookies with Angular Universal and Node.js)

To accomplish the tasks in this post you will need the following:

要完成本文中的任务,您将需要以下内容:

To learn most effectively from this post you should have the following:

要从这篇文章中最有效地学习,您应该具备以下条件:

There is a companion repository for this post available on GitHub.

在GitHub上有此文章的配套存储库

为组件和服务创建项目和文件 (Create the project and files for the components and services)

In this step you will initialize the Angular project with npm. You will also add server-side rendering, create a sign in page, a home page, and two services.

在这一步中,您将使用npm初始化Angular项目。 您还将添加服务器端渲染,创建登录页面,主页和两个服务。

Go to the directory under which you’d like to create the project and execute the following command line instructions to initialize the project and add server-side rendering:

转到要在其下创建项目的目录,并执行以下命令行指令以初始化项目并添加服务器端渲染:

ng new encrypted-rsa-cookie-nodejs --style css --routing true
cd encrypted-rsa-cookie-nodejs
ng add @ng-toolkit/universal
npm install cookie-parser

Execute the following command line instructions to create the AuthorizationService and AuthGuardServiceservice classes:

执行以下命令行指令以创建AuthorizationServiceAuthGuardService服务类:

ng g s authorization --skipTests
ng g s authGuard --skipTests

Execute the following commands to create the SigninPageComponent and ProtectedPageComponent component classes:

执行以下命令来创建SigninPageComponentProtectedPageComponent组件类:

ng g c signinPage --skipTests  --module app.module.ts
ng g c protectedPage --skipTests --module app.module.ts

实施服务器和RESTful端点 (Implement the server and RESTful endpoints)

This step implements the Node.js server and the API endpoints, and it creates a couple users for demonstrating the application’s functionality. In a production application you would be validating the user sign in information against a persistent data store, like a database, and you’d be doing some cryptography with that as well so you don’t get caught storing secrets like passwords in plaintext. In this app you’ll be hard-coding them for simplicity’s sake.

此步骤实现了Node.js服务器和API端点,并创建了几个用户来演示应用程序的功能。 在生产应用程序中,您将针对持久性数据存储(例如数据库)验证用户登录信息,并且还将对其进行一些加密,因此不会被捕获以明文形式存储密码之类的机密信息。 在这个应用程序中,为简单起见,您将对其进行硬编码。

Replace contents of the server.ts file with the following TypeScript code:

用以下TypeScript代码替换server.ts文件的内容:

import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import {enableProdMode} from '@angular/core';
import {ngExpressEngine} from '@nguniversal/express-engine';
import {provideModuleMap} from '@nguniversal/module-map-ngfactory-loader';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as cors from 'cors';
import * as compression from 'compression';
import * as cookieParser from 'cookie-parser';
enableProdMode();
export const app = express();
app.use(compression());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main');
const users = [
 { uid: '1', username: 'john', password: 'abc123', mySecret: 'I let my cat eat from my plate.' },
 { uid: '2', username: 'kate', password: '123abc', mySecret: 'I let my dog sleep in my bed.'}
];
app.engine('html', ngExpressEngine({
 bootstrap: AppServerModuleNgFactory,
 providers: [
   provideModuleMap(LAZY_MODULE_MAP)
 ]
}));
app.set('view engine', 'html');
app.set('views', './dist/browser');
app.post('/auth/signIn', (req, res) => {
 const requestedUser = users.find( user => {
   return user.username === req.body.username && user.password === req.body.password;
 });
 if (requestedUser) {
   res.cookie('authentication', requestedUser.uid, {
     maxAge: 2 * 60 * 60 * 60,
     httpOnly: true
   });
   res.status(200).send({status: 'authenticated'});
 } else {
   res.status(401).send({status: 'bad credentials'});
 }
});
app.get('/auth/isLogged', (req, res) => {
 res.status(200).send({authenticated: !!req.cookies.authentication});
});
app.get('/auth/signOut', (req, res) => {
 res.cookie('authentication', '', {
   maxAge: -1,
   httpOnly: true
 });
 res.status(200).send({status: 'signed out'});
});
app.get('/secretData', (req, res) => {
 const uid = req.cookies.authentication;
 res.status(200).send({secret: users.find(user => user.uid === uid).mySecret});
});
app.get('*.*', express.static('./dist/browser', {
 maxAge: '1y'
}));
app.get('/*', (req, res) => {
 res.render('index', {req, res}, (err, html) => {
   if (html) {
     res.send(html);
   } else {
     console.error(err);
     res.send(err);
   }
 });
});

In the code above, note the two users john and kate, and their uid values, passwords, and secrets. They’ll appear later.

在上面的代码中,请注意两个用户johnkate ,以及他们的uid值,密码和机密。 他们会在以后出现。

If you are an eagle-eyed and experienced JavaScript developer you will have noted the use of JavaScript double-negation in the /auth/isLogged endpoint. This is a way of determining the truthiness of an object. There is a Stack Overflow Q&A on the subject of not-not with extensive commentary, but the easiest — and by far the drollest — way to remember what is does was provided by Gus in 2012: “bang, bang; you’re boolean”.

如果您是一位鹰眼且经验丰富JavaScript开发人员,您将注意到/ auth / isLogged端点中使用了JavaScript双重否定。 这是确定对象真实性的一种方法。 关于这个问题,有一个堆栈溢出问答,内容不那么广泛,但有一种最简单的方法(到目前为止也是最乏味的)来记住古斯在2012年所做的事情:“砰,砰;砰! 你是布尔值”。

Also note the API endpoint responsible for user authorization: /auth/signIn. Whenever the username and password match, the code sets up an httpOnly cookie on the client side. The cookie isn’t encrypted at this point, so you’ll be able to read and change the contents with the EditThisCookie extension for Chrome.

还要注意负责用户授权的API端点: / auth / signIn 。 只要用户名和密码匹配,代码就会在客户端设置一个httpOnly cookie。 Cookie目前尚未加密,因此您可以使用适用于Chrome的EditThisCookie扩展程序来读取和更改内容。

app.post('/auth/signIn', (req, res) => {
 const requestedUser = users.find( user => {
   return user.username === req.body.username && user.password === req.body.password;
 });
 if (requestedUser) {
   res.cookie('authentication', requestedUser.uid, {
     maxAge: 2 * 60 * 60 * 60,
     httpOnly: true
   });
   res.status(200).send({status: 'authenticated'});
 } else {
   res.status(401).send({status: 'bad credentials'});
 }
});

The presence of the cookie indicates a user is signed in:

Cookie的存在指示用户已登录:

app.get('/auth/isLogged', (req, res) => {
 res.status(200).send({authenticated: !!req.cookies.authentication});
});

If a user signs out, all that needs to happen is to remove the authenticated user’s cookie:

如果用户退出,那么所有要做的就是删除经过身份验证的用户的cookie:

app.get('/auth/signOut', (req, res) => {
 res.cookie('authentication', '', {
   maxAge: -1,
   httpOnly: true
 });
 res.status(200).send({status: 'signed out'});
});

Another endpoint responds with data from the user’s record in the users array:

另一个端点使用users数组中用户记录的数据进行响应:

app.get('/secretData', (req, res) => {
 const uid = req.cookies.authentication;
 res.status(200).send({secret: users.find(user => user.uid === uid).mySecret});
});

创建组件和服务 (Create components and services)

The server’s API endpoints are going to be consumed in two places, the ProtectedPageComponent and AuthorizationService classes. The ProtectedPageComponent class displays the user data stored in the mySecret field of the users array.

服务器的API端点将在两个位置使用,即ProtectedPageComponentAuthorizationService类。 ProtectedPageComponent类显示存储在users数组的mySecret字段中的users

Replace the contents of the src/app/protected-page/protected-page.component.ts file with the following TypeScript code:

用以下TypeScript代码替换src / app / protected-page / protected-page.component.ts文件的内容:

import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Component({
 selector: 'app-protected-page',
 templateUrl: './protected-page.component.html',
 styleUrls: ['./protected-page.component.css']
})
export class ProtectedPageComponent {
 public mySecret: Observable<string> = this.http.get<any>('/secretData').pipe(map(resp => resp.secret));
 constructor(private http: HttpClient) { }
}

Replace content of the src/app/protected-page/protected-page.component.html file with following HTML markup:

用以下HTML标记替换src / app / protected-page / protected-page.component.html文件的内容:

<p>
 My secret is: {{mySecret | async}}
</p>
<button (click)="signOut()">Sign Out</button>

Of course, customer secrets should be available only to them. An AuthorizationService class will provide the functionality necessary to sign the user into the app and redirect them to the target URL containing the user secret: /protected-page.

当然,客户机密应该仅对他们可用。 AuthorizationService类将提供将用户登录到应用程序并将其重定向到包含用户密码的目标URL所需的功能: / protected-page

The class also returns two observables, one that indicates if the user is signed in, and another that sets the user’s status to ‘signed out’ and redirects them from /protected-page (or any page requiring a signed-in user) to /signin.

该类还返回两个可观察值,一个指示用户是否已登录,另一个将用户的状态设置为“已退出”,并将其从/ protected-page (或任何需要登录用户的页面)重定向到/登录

Replace the contents of the src/app/authorization.service.ts file with the following TypeScript code:

用以下TypeScript代码替换src / app / authorization.service.ts文件的内容:

import { Injectable, Inject, PLATFORM_ID, Optional } from '@angular/core';
import { Router } from '@angular/router';
import { HttpClient } from '@angular/common/http';
import { map, tap } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { isPlatformServer } from '@angular/common';
import { REQUEST } from '@nguniversal/express-engine/tokens';
@Injectable({
providedIn: 'root'
})
export class AuthorizationService {
 private redirectUrl: string = '/';
 constructor(
   private router: Router,
   private http: HttpClient,
   @Inject(PLATFORM_ID) private platformId: any,
   @Optional() @Inject(REQUEST) private request: any
 ) { }
 public setRedirectUrl(url: string) {
   this.redirectUrl = url;
 }
 public signIn(username: string, password: string): Observable<any> {
   return this.http.post<any>('/auth/signIn', {username: username, password: password}).pipe(
     tap(_ => {
       this.router.navigate([this.redirectUrl]);
     })
   );
 }
 public isAuthenticated(): Observable<boolean> {
   if (isPlatformServer(this.platformId)) {
     return of(this.request.cookies.authentication);
   }
   return this.http.get<any>('/auth/isLogged').pipe(map(response => response.authenticated));
 }
 public signOut(): Observable<boolean> {
   return this.http.get<any>('/auth/signOut').pipe(
     map(response => response.status === 'signed out'),
     tap( _ => this.router.navigate(['signin']) )
     );
 }
}

Now that the AuthorizationService class is implemented you can make use of it in the logic for a signOutbutton.

现在已经实现了AuthorizationService类,您可以在signOut按钮的逻辑中使用它。

Add the following import statement at the top of the src/app/protected-page/protected-page.component.ts file:

src / app / protected-page / protected-page.component.ts文件的顶部添加以下导入语句:

import { AuthorizationService } from '../authorization.service';

Modify the ProtectedPageComponent class constructor in the same file to read as follows:

修改同一文件中的ProtectedPageComponent类构造函数,使其内容如下:

constructor(private http: HttpClient, private authService: AuthorizationService) { }

Add the following code to the bottom of the protected-page.component.ts file to implement the signOut method:

下面的代码添加到受保护的,page.component.ts文件的底部实现signOut 方法:

public signOut(): void {
   this.authService.signOut().subscribe();
}

The AuthorizationService class is also used by the AuthGuardService class, which you can implement now.

AuthorizationService类也使用AuthGuardService类,你现在可以实现。

Replace contents of the src/app/auth-guard.service.ts file with this TypeScript code:

使用以下TypeScript代码替换src / app / auth-guard.service.ts文件的内容:

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthorizationService } from './authorization.service';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
 constructor(private authService: AuthorizationService, private router: Router) { }
 public canActivate(): Observable<boolean> {
   return this.authService.isAuthenticated().pipe(map(isAuth => {
     if (!isAuth) {
       this.authService.setRedirectUrl(this.router.url);
       this.router.navigate(['signin']);
     }
     return isAuth;
   }));
 }
}

The AuthGuardService class is used to protect routes and pages requiring a user to be authenticated and authorized in order to access them. In this application, the /home route is implemented with the ProtectedPageComponent. The AuthGuardService class implements the CanActivate interface, which enables Angular routing to invoke the service when the route is activated.

AuthGuardService类用于保护路由和页面,这些路由和页面要求对用户进行身份验证和授权才能访问它们。 在此应用程序中, / home路由是通过ProtectedPageComponent实现的。 AuthGuardService类实现CanActivate接口,该接口使Angular路由在激活路由时可以调用服务。

As you can see in the code above, whenever unauthenticated users are redirected to the /signin page.

如您在上面的代码中看到的,每当未经身份验证的用户被重定向到/ signin页面时。

Implement the /signin page by replacing the contents of src/app/signin-page/signin-page.component.ts with the following TypeScript code:

通过替换的src /应用/登入页/登入-page.component.ts用下面的打字稿代码的内容执行/登录页面:

import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { AuthorizationService } from '../authorization.service';
@Component({
 selector: 'app-signin-page',
 templateUrl: './signin-page.component.html',
 styleUrls: ['./signin-page.component.css']
})
export class SigninPageComponent {
 public signinForm: FormGroup = new FormGroup({
   username: new FormControl(''),
   password: new FormControl('')
 });
 constructor(private authService: AuthorizationService) { }
 public onSubmit(): void {
   this.authService.signIn(
     this.signinForm.get('username').value,
     this.signinForm.get('password').value
   ).subscribe();
 }
}

Implement the template for the /signin page by replacing the contents of the src/app/signin-page/signin-page.component.html file with the following HTML markup:

通过使用以下HTML标记替换src / app / signin-page / signin-page.component.html文件的内容,为/ signin页面实现模板。

<form [formGroup]="signinForm" (ngSubmit)="onSubmit()">
 <label>Username: </label><input type="text" formControlName="username" /><br/>
 <label>Password: </label><input type="password" formControlName="password"/><br/>
 <input type="submit" value="Sign In" />
</form>

To work with the FormGroup object introduced in the SigninPageComponent you need to import ReactiveFormsModule in the AppModule class.

为了与工作FormGroup在介绍对象SigninPageComponent需要进口ReactiveFormsModuleAppModule类。

Insert the following import statement into the src/app/app.module.ts file:

将以下import语句插入src / app / app.module.ts文件:

import { ReactiveFormsModule } from '@angular/forms';

And add it to the imports array of the @NgModule decorator as follows:

并将其添加到@NgModule装饰器的imports数组中,如下所示:

imports:[
   ReactiveFormsModule,
   CommonModule,
   NgtUniversalModule,
   TransferHttpCacheModule,
   HttpClientModule,
   AppRoutingModule
],

The services and components all come together in the application’s routing directives.

服务和组件都在应用程序的路由指令中组合在一起。

Replace the contents of the src/app/app-routing.module.ts file with the following TypeScript code:

用以下TypeScript代码替换src / app / app-routing.module.ts文件的内容:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ProtectedPageComponent } from './protected-page/protected-page.component';
import { SigninPageComponent } from './signin-page/signin-page.component';
import { AuthGuardService } from './auth-guard.service';
const routes: Routes = [
 { path: '', redirectTo: 'home', pathMatch: 'full' },
 { path: 'signin', component: SigninPageComponent },
 { path: 'home', component: ProtectedPageComponent, canActivate: [AuthGuardService] },
];
@NgModule({
 imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
export class AppRoutingModule { }

Remove all the contents of the src/app/app.component.html file except the routerOutlet element:

除去src / app / app.component.html文件的所有内容,但routerOutlet元素除外:

<router-outlet></router-outlet>

If you want to catch up to this step using the code from the GitHub repository, execute the following commands in the directory where you’d like to create the project directory:

如果您想使用GitHub存储库中的代码来完成此步骤,请在要创建项目目录的目录中执行以下命令:

git clone https://github.com/maciejtreder/encrypted-rsa-cookie-nodejs.git
cd encrypted-rsa-cookie-nodejs
git checkout step1
npm install

构建并测试应用程序 (Build and test the application)

To build and run the application, execute the following npm command line instructions in the encrypted-rsa-cookie-nodejs directory:

要构建和运行该应用程序,请在encrypted-rsa-cookie-nodejs目录中执行以下npm命令行说明:

npm run build:prod
npm run server

Navigate to http://localhost:8080 with your browser.

使用浏览器导航到http:// localhost:8080

You should be redirected to the /signin page, as shown below. This demonstrates that the AuthGuardServiceand routing are working as intended.

您应该重定向到/ signin页面,如下所示。 这表明AuthGuardService和路由可以按预期工作。

Image for post

Enter the credentials of the first test user (defined in the server.ts file).

输入第一个测试用户的凭据(在server.ts文件中定义)。

Username: john Password: abc123

用户名:john密码:abc123

Click the Sign In button.

单击登录按钮。

You should see a feline-related secret. This demonstrates that the user is authenticated and allowed to access the /home route and also authorized see the mySecret data for uid 1, john. The application should appear in the browser as in the illustration below:

您应该看到猫科动物相关的秘密。 这表明用户已通过身份验证并被允许访问/ home路由,并且还被授权查看uid 1,john的mySecret数据。 该应用程序应出现在浏览器中,如下图所示:

Image for post

Now check Kate’s credentials.

现在检查Kate的凭据。

Click the Sign Out button and enter the credentials for uid 2.

单击“ 注销” button and enter the credentials for uid 2. button and enter the credentials for 2.

Username: kate Password: 123abc

用户名:kate密码:123abc

Click the Sign In button.

单击登录按钮。

You should see a canine-related secret. This demonstrate that the values of mySecret are being correctly retrieved based on the value of uid in the users array in the server.ts file. Your results should be similar to those shown below.

您应该看到与犬有关的秘密。 这表明,mySecret的值are being correctly retrieved based on the value of UID in the的用户array in the server.ts file. Your results should be similar to those shown below. array in the server.ts file. Your results should be similar to those shown below.

Image for post

Both users need to use their credentials to see their secret data.

两个用户都需要使用其凭据来查看其秘密数据。

But can they see only their own secret data?

但是他们只能看到自己的秘密数据吗?

Examine how the /secretData endpoint in the server.ts file determines how to find the value of mySecret`:

检查server.ts文件中的/ secretData端点如何确定如何查找mySecret`的值:

app.get('/secretData', (req, res) => {
  let uid = req.cookies.authentication;
  res.status(200).send({secret: users.find(user => user.uid === uid).mySecret});
});

The server code reads the contents of the authorization cookie received with the request. Based on the value of uid, it looks for the corresponding user in the users array and returns value of the mySecret field for the user. The cookie has an httpOnly attribute, so it can’t be read by malicious JavaScript code and compromised by a hacker.

服务器代码读取与请求一起收到的授权cookie的内容。 基于uid的值,它将在users数组中寻找相应的用户,并为该users返回mySecret字段的值。 Cookie具有httpOnly属性,因此恶意JavaScript代码无法读取它,黑客也无法对其进行破坏。

But what happens if Kate signs into the application and changes her cookie value manually? You can simulate that with the EditThisCookie extension for Google Chrome.

但是,如果Kate登录到应用程序并手动更改其cookie值,会发生什么? 您可以使用适用于Google Chrome的EditThisCookie扩展程序进行模拟。

Install the EditThisCookie extension, then follow these steps with the application running:

安装EditThisCookie扩展,然后在应用程序运行时执行以下步骤:

  1. Navigate to http://localhost:8080

    导航到http:// localhost:8080

  2. Sign in using Kate’s credentials: username: kate, password: 123abc

    使用Kate的凭据登录:用户名:kate,密码:123abc
  3. Click on the EditThisCookie icon in the top right corner (next to the address bar)

    单击右上角(地址栏旁边)的EditThisCookie图标
  4. Click on the authentication cookie and change its value from 2 to 1

    单击authentication cookie并将其值从2更改为1

  5. Reload the page

    重新载入页面
Image for post

Ooops. An unauthorized access to data! Kate is able to see the canine secret associated with John.

哎呀 未经授权访问数据! 凯特能够看到与约翰有关的犬科秘方。

加密cookie (Encrypt the cookie)

You can prevent unauthorized access to data stored in cookies with encryption. Because the cookie data won’t be shared with any other system (a third-party system or an internal system like a microservices architecture) only a private RSA key is necessary. This makes the key easy to generate and use.

您可以通过加密防止未经授权访问存储在Cookie中的数据。 因为cookie数据不会与任何其他系统(第三方系统或微服务体系结构之类的内部系统)共享,所以仅需要一个专用 RSA 密钥。 这使得密钥易于生成和使用。

Windows用户 (Windows users)

If you have installed Git, you can find the openssl.exe executable in the C:\Program Files\Git\usr\bin directory. Note that this directory may not be included in your path and you will need write access to the target directory to create the privkey.pem file. Regardless of where you generate the file, its final destination should be the encrypted-ras-cookie-nodejs directory.

如果已安装Git,则可以在C:\ Program Files \ Git \ usr \ bin目录中找到openssl.exe可执行文件 。 请注意,此目录可能不包含在您的路径中,并且您需要对目标目录具有写访问权才能创建privkey.pem文件。 无论您在何处生成文件,其最终目的地都应该是crypto-ras-cookie-nodejs目录。

macOS用户 (macOS users)

On macOS, you can install an OpenSSL by using brew package manager:

在macOS上,可以使用brew软件包管理器安装OpenSSL:

brew update
brew install openssl
echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile

Linux用户 (Linux users)

If you are Linux user you can install OpenSSL using the default package manager for your system. For example, Ubuntu users can use apt-get:

如果您是Linux用户,则可以使用系统的默认软件包管理器来安装OpenSSL。 例如,Ubuntu用户可以使用apt-get

apt-get install openssl

In keeping with the preceding prerequisites for your operating system, execute the following command line instruction to generate the private RSA key:

为了符合您的操作系统的前提条件,请执行以下命令行指令以生成私有RSA密钥:

openssl genrsa -out ./privkey.pem 2048

The key you generated is going to be used in the encrypt() and decrypt() methods in the server.ts file.

您生成的密钥将在server.ts文件的crypto encrypt()decrypt()方法中使用。

Insert the following TypeScript code after the users array initialization in the server.ts file:

users数组初始化之后,在server.ts文件中插入以下TypeScript代码:

const crypto = require('crypto');
const path = require('path');
const fs = require('fs');
const key = fs.readFileSync(path.resolve('./privkey.pem'), 'utf8');


function encrypt(toEncrypt: string): string {
 const buffer = Buffer.from(toEncrypt);
 const encrypted = crypto.privateEncrypt(key, buffer);
 return encrypted.toString('base64');
}


function decrypt(toDecrypt: string): string {
 const buffer = Buffer.from(toDecrypt, 'base64');
 const decrypted = crypto.publicDecrypt(key, buffer);
 return decrypted.toString('utf8');
}

Now you can change implementations of the /auth/signin and /secretData endpoints in server.ts:

现在,您可以在server.ts中更改/ auth / signin/ secretData端点的实现:

app.post('/auth/signin', (req, res) => {
 const requestedUser = users.find( user => {
   return user.username === req.body.username && user.password === req.body.password;
 });
 if (requestedUser) {
   res.cookie('authentication', encrypt(requestedUser.uid), {
     maxAge: 2 * 60 * 60 * 60,
     httpOnly: true
   });
   res.status(200).send({status: 'authenticated'});
 } else {
   res.status(401).send({status: 'bad credentials'});
 }
});




app.get('/secretData', (req, res) => {
 const uid = decrypt(req.cookies.authentication);
 res.status(200).send({secret: users.find(user => user.uid === uid).mySecret});
});

As you can see, the /auth/signin endpoint now uses the crypto library and the privkey.pem key to encrypt the value of the authentication cookie. The /secretData endpoint decrypts the value of mySecret based on the encrypted value of uid, which is highly resistant to being hacked. Only if the encrypted value of uid matches a value in the users data store is an associated value for mySecret returned.

如您所见, / auth / signin端点现在使用crypto库和privkey.pem密钥来加密authentication cookie的值。 / secretData终结mySecret基于uid的加密值解密mySecret的值,该值具有极高的抗黑客能力。 仅当uid的加密值与users数据存储中的值匹配时, mySecret返回mySecret的关联值。

If you want to catch up to this step using the code from the companion GitHub repository, execute the following command line instructions in the directory where you’d like to create the project directory:

如果您想使用随附的GitHub存储库中的代码来完成此步骤,请在您要创建项目目录的目录中执行以下命令行说明:

git clone https://github.com/maciejtreder/encrypted-rsa-cookie-nodejs.git
cd encrypted-rsa-cookie-nodejs
git checkout step2
npm install

重建并测试应用程序 (Rebuild and test the application)

To rebuild and run the application, execute the following command line instructions in the encrypted-rse-cookie-nodejs directory:

要重建并运行该应用程序,请在encrypted-rse-cookie-nodejs目录中执行以下命令行指令:

npm run build:prod
npm run server

Navigate to http://localhost:8080 with Google Chrome. Sign in using the credentials of one of the test users (john or kate). Using EditThisCookie, check the value of the authenticated cookie. You should see a string like se43zECwOjU8LAvaVl8fIqOLOzYAVTQoGZKVi2fqg54tmDaapm... in the Value field.

使用Google Chrome浏览到http:// localhost:8080 。 使用测试用户之一(john或kate)的凭据登录。 使用EditThisCookie,检查经过authenticated cookie的值。 您应该在“ 值”字段中看到一个字符串,例如se43zECwOjU8LAvaVl8fIqOLOzYAVTQoGZKVi2fqg54tmDaapm...

Your actual value will be determined by the encryption algorithm, so it will be different. This value is substantially more difficult to interpret and change than the 1 or 2 used when this was a plaintext field. It would be almost equally difficult to change successfully if it was an email address or an order number.

您的实际值将由加密算法确定,因此会有所不同。 与纯文本字段时使用的12相比,此值实质上难以解释和更改。 如果是电子邮件地址或订单号,则成功更改几乎同样困难。

The results are illustrated in the screenshot below. Note that the HttpOnly field is checked, so the cookie is still inaccessible to JavaScript running on the client.

结果在下面的屏幕快照中说明。 请注意,已选中HttpOnly字段,因此仍无法在客户端上运行JavaScript访问cookie。

Image for post

Experiment with signing out as one user and signing in as another to see how the AuthGuardService class and other components govern the application’s routing.

尝试以一个用户身份AuthGuardService并以另一个用户身份登录,以查看AuthGuardService类和其他组件如何控制应用程序的路由。

Finally, note that the EditThisCookie extension for Chrome has a lot of power. You may want to disable it when you’re not using it, or uninstall it.

最后,请注意,Chrome的EditThisCookie扩展功能强大。 您可能想在不使用它时禁用它,或者将其卸载。

使用Angular Universal和Node.js加密cookie中的加密数据摘要 (Summary of encrypting data in Encrypting cookies with Angular Universal and Node.js)

Beware! Your “trusted user” might not be trustworthy.

谨防! 您的“受信任用户”可能不可信。

To protect your customers you need to consider every possible way in which the security of your application might be compromised and then implement an effective response. Storing values outside of the app in encrypted form is one of the steps which brings you closer to effective security.

为了保护您的客户,您需要考虑各种可能破坏应用程序安全性的方法,然后实施有效的响应。 将值以加密形式存储在应用程序外部是使您更接近有效安全性的步骤之一。

In this post you learned how to use an authentication cookie to restrict access to user secrets by using the data in the cookie to perform authorization functions. You saw a first-hand example of how unauthorized modification of a cookie value can result in unauthorized access to confidential data. Most importantly, you learned a technique for encrypting cookie fields to prevent unauthorized modification of their values.

在本文中,您学习了如何使用身份验证cookie通过使用cookie中的数据执行授权功能来限制对用户机密的访问。 您看到了一个第一手的示例,该示例说明了未经授权修改Cookie值如何导致未经授权访问机密数据。 最重要的是,您学习了一种加密cookie字段的技术,以防止未经授权对其值进行修改。

额外资源 (Additional resources)

For more information about security and authorization check out these previous posts on the Twilio blog:

有关安全性和授权的更多信息,请查看Twilio博客上的以下先前文章:

I’m Maciej Treder, contact me via contact@maciejtreder.com, https://www.maciejtreder.com or @maciejtreder on GitHub, Twitter and LinkedIn.

我马切伊Treder,通过接触我 contact@maciejtreder.com https://www.maciejtreder.com 或@maciejtreder在 GitHub上 Twitter的 LinkedIn

This post is originally published on the Twilio Blog.

该帖子最初发布在 Twilio博客上

翻译自: https://medium.com/swlh/encrypting-cookies-with-angular-universal-and-node-js-4f5ee5c65083

zookeeper节点加密

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值