Introduction

OAuth 2 is an authorization framework that enables applications to obtain limited access to user accounts on an HTTP service, such as Facebook, GitHub, and DigitalOcean. It works by delegating user authentication to the service that hosts the user account, and authorizing third-party applications to access the user account. OAuth 2 provides authorization flows for web and desktop applications, and mobile devices.

OAuth Roles

  • Resource Owner (user)

    The resource owner is the user who authorizes an application to access their account. The application’s access to the user’s account is limited to the “scope” of the authorization granted (e.g. read or write access).

  • Client (application)

    The client is the application that wants to access the user’s account. Before it may do so, it must be authorized by the user, and the authorization must be validated by the API.

  • Resource Server

    The resource server hosts the protected resource user would like to access. The resource server validates the access token, and if valid, serves the request.

  • Authorization Server

    The authorization server verifies the identity of the user and then issues access tokens to the application.

Abstract Protocol Flow

abstract_flow

Detailed explanation of the steps in the diagram:

  1. The application requests authorization to access service resources from the user.
  2. If the user authorized the request, the application receives an authorization grant.
  3. The application requests an access token from the authorization server (API) by presenting authentication of its own identity, the authorization grant.
  4. If the application identity is authenticated and the authorization grant is valid, the authorization server (API) issues an access token to the application. Authorization is complete.
  5. The application requests the resource from the resource server (API) and presents the access token for authentication.
  6. If the access token is valid, the resource server (API) serves the resource to the application.

Example

oauthv2-microsoft-identity

Take an example, we develop an app and hopes user can view his profile from the app, where user’s profile info is stored in Microsoft Graph Service. In this scenario, roles are as below:

  • Resource Onwer: user
  • Client: the application
  • Resource Server: The Microsoft Graph Server
  • Authorization Server (the identity provider): Azure Activity Directory (AAD)

To realize the OAuth flow, we register an app registration on AAD for our application. When user want to get his profile when using the app:

  1. Our app ask user for authorization grant
  2. User consent the scope the app ask for the graph server.
  3. With the authorization grant, the app can ask AAD for access token to get profile from the Graph Server.
  4. The AAD server validate the authorization grant and give the access token to the app.
  5. With the access token, the app is able to turn to the Graph Server to get user’s profile.

Authentication VS Authorization

  • Authentication 验证

    Authentication is the process of proving that you are who you say you are.

    The Microsoft identity platform uses the OpenID Connect protocol for handling authentication.

  • Authorization 授权

    Authorization is the act of granting an authenticated party permission to do something. It specifies what data you’re allowed to access and what you can do with that data.

    The Microsoft identity platform uses the OAuth 2.0 protocol for handling authorization.

Authorization Grant Types

  1. Authorization Code: used with server-side Applications
  2. Implicit: used with Mobile Apps or Web Applications (applications that run on the user’s device)
  3. Resource Owner Password Credentials: used with trusted Applications, such as those owned by the service itself
  4. Client Credentials: used with Applications API access

Authorization Code

The authorization code grant type is the most commonly used because it is optimized for server-side applications, where source code is not publicly exposed, and Client Secret confidentiality can be maintained. This is a redirection-based flow, which means that the application must be capable of interacting with the user-agent (i.e. the user’s web browser) and receiving API authorization codes that are routed through the user-agent.

授权码(authorization code)方式,指的是第三方应用先申请一个授权码,然后再用该码获取令牌。

这种方式是最常用的流程,安全性也最高,它适用于那些有后端的 Web 应用。授权码通过前端传送,令牌则是储存在后端,而且所有与资源服务器的通信都在后端完成。这样的前后端分离,可以避免令牌泄漏。

auth_code_flow

1
https://cloud.digitalocean.com/v1/oauth/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=CALLBACK_URL&scope=read

Here is an explanation of the link components:

  • https://cloud.digitalocean.com/v1/oauth/authorize: the API authorization endpoint
  • client_id=client_id: the application’s client ID (how the API identifies the application)
  • redirect_uri=CALLBACK_URL: where the service redirects the user-agent after an authorization code is granted
  • response_type=code: specifies that your application is requesting an authorization code grant
  • scope=read: specifies the level of access that the application is requesting

Step 2: User Authorizes Application

When the user clicks the link, they must first log in to the service, to authenticate their identity (unless they are already logged in). Then they will be prompted by the service to authorize or deny the application access to their account.

Step 3: Application Receives Authorization Code

If the user clicks “Authorize Application”, the service redirects the user-agent to the application redirect URI, which was specified during the client registration, along with an authorization code.

1
https://dropletbook.com/callback?code=AUTHORIZATION_CODE

Step 4: Application Requests Access Token

1
https://cloud.digitalocean.com/v1/oauth/token?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&grant_type=authorization_code&code=AUTHORIZATION_CODE&redirect_uri=CALLBACK_URL

Step 5: Application Receives Access Token

1
{"access_token":"ACCESS_TOKEN","token_type":"bearer","expires_in":2592000,"refresh_token":"REFRESH_TOKEN","scope":"read","uid":100101,"info":{"name":"Mark E. Mark","email":"mark@thefunkybunch.com"}}

Implicit

The implicit grant type is used for mobile apps and web applications (i.e. applications that run in a web browser), where the client secret confidentiality is not guaranteed. The implicit grant type is also a redirection-based flow but the access token is given to the user-agent to forward to the application, so it may be exposed to the user and other applications on the user’s device. Also, this flow does not authenticate the identity of the application, and relies on the redirect URI (that was registered with the service) to serve this purpose.

The implicit grant type does not support refresh tokens.

The implicit grant flow basically works as follows: the user is asked to authorize the application, then the authorization server passes the access token back to the user-agent, which passes it to the application. If you are curious about the details, read on.

有些 Web 应用是纯前端应用,没有后端。这时就不能用上面的方式了,必须将令牌储存在前端。RFC 6749 就规定了第二种方式,允许直接向前端颁发令牌。这种方式没有授权码这个中间步骤,所以称为(授权码)”隐藏式”(implicit)。

implicit_flow

1
https://cloud.digitalocean.com/v1/oauth/authorize?response_type=token&client_id=CLIENT_ID&redirect_uri=CALLBACK_URL&scope=read

Step 2: User Authorizes Application

注意,令牌的位置是 URL 锚点(fragment),而不是查询字符串(querystring),这是因为 OAuth 2.0 允许跳转网址是 HTTP 协议,因此存在”中间人攻击”的风险,而浏览器跳转时,锚点不会发到服务器,就减少了泄漏令牌的风险。

Resource Owner Password Credentials

Client Credentials

More Read

Ref

Digital Signature

What is Digital Signature

A digital signature is equivalent to a handwritten signature in paper. It is an electronic verification of the sender.

A digital signature serves three basic purposes.

  • Authentication
  • Non-repudiation
  • Integrity

How Digital Signature Works

what-is-digital-signature

Keep in mind, digital signature is not about encrypting document, just like paper-based signature.

Weakness of Digital Signature

Digital signature lacks authentication! (Anyone can pretend he is Bob.)

Man-in-the-middle attack:

Man-in-the-middle-attack-1

Man-in-the-middle-attack-2

So we need digital certificate!

Digital Certificate

Digital certificates are electronic credentials issued by a trusted third party.

Why Do We Need Digital Certificate

Because digital certificate verifies not only the identity of the owner, but also that the owner owns the public key.

Digital certificate verifies the digital signature is truly signed by the claimed signer.

How SSL Certificate Works

Prerequisites

pre

SSL Certificate Flow

ssl-cer-flow

Signed on Trusted Third Party CA (eg. Google CA)

cer-with-gg

Self-Signed Certificate

self-sign-cer

More Read

Ref

SSL/TLS Operation Layer

operation-layer

The SSL/TLS protocol operates on:

  • Application / Presentation / Session layers of OSI model
  • Application layer of TCP/IP model

SSL/TLS Handshake Process

handshake-all

Step 1 ClientHello

step1

Step 2 ServerHello

step2

Step 3 Verify Digital Certificate

step3
The client will contact the server’s CA(certificate authority) and verify the server’s digital certificate, thus confirming the authenticity of the web server.
GOAL: Establishing the trust on the web server.

Step 4 ClientKeyExchange

step4

Step 5 Finished(client)

step5

Step 6 Finished(server)

step6

Step 7 Handshake Done. Exchanged Message

step7
Once the handshake is done, the server and client can now exchange messages that are symmetrically encrypted with the shared secret key.

Notes

  1. The above process demonstrates how asymmetric key algorithm and symmetric key algorithm work together.
  • Asymmetric key algorithm (public key & private key) is used to verify the identity of the owner and its public key so that trust is built.
  • Once the connection is established, Symmetric key algorithm (shared key) is used to encrypt and decrypt all traffic between them.
  1. The green padlock: indicates that the web server’s public key really belongs to the web server, not someone else.

  2. The Https and the green padlock only indicates the communications between client and server are encrypted. It does not says the website is “safe and good”.

More Read

Ref

Definition

HTTP: Hypertext Transfer Protocol

  • Clear text
  • Vulnerable to hackers

HTTPS: Secure Hypertext Transfer Protocol

  • Encrypted text
  • HTTP over Secure Socket Layer(SSL)

SSL: Secure Sockets Layer

  • Protocol that’s used to ensure security on the internet.
  • Use public key encryption to secure data.

TLS: Transport Layer Security

  • The latest industry standard cryptographic protocol.
  • The successor to SSL.
  • Authenticates the server, client and encrypts the data.

More Read

Ref

node logo

Unit 1: Overview of Node.js Learning Path

Unit 2: Installing Node.js, npm, and VSCode

Install Node and Npm

  1. Install from nodejs.org

  2. Install Node & Npm via node version manager (nvm)

  3. Use Npx

Unit 3: A tour of Node.js

Node.js Architecture

Node.js is a JavaScript runtime built on Chrome V8 JavaScript engine.

node architecture

ECMAScript Standard

Read-Eval-Print-Loop (REPL)

npm

npm consists of:

Unit 4: Node.js basic concepts

Node Modules

In the Node.js module system, each file is treated as a separate module.

Non-blocking I/O

Overview of Blocking vs Non-Blocking

Load Testing

Consider case where each request to a web server takes 50ms to complete and 45ms of that 50ms is database I/O that can be done asynchronously. Choosing non-blocking asynchronous operations frees up that 45ms per request to handle other requests. This is a significant difference in capacity just by choosing to use non-blocking methods instead of blocking methods.

Unit 5: The event loop

A complete guide to the Node.js event loop

Unit 8: Node dependency management

  1. Semantic version (semver)

    • npm semver calculator: https://semver.npmjs.com/
    • caret (aka hat) symbol, ^ : include everything that does not increment the first non-zero portion of semver.
      1
      "^2.1.9": >= 2.1.9 and < 3.0.0 
    • tilde symbol, ~ : include everything greater than a particular version in the same minor range.
      1
      "~2.1.9": >= 2.1.9 and < 2.2.0
  2. Visualization of npm dependencies: http://npm.anvaka.com/

Unit 9: Unit testing and linting with Node.js

There are two aspects to code quality that you can automate.

  • Testing
    • A test framework [Mocha.js]
    • An assertion library (if the framework doesn’t come with one) [Chai.js]
    • A test doubles library (again, if the framework doesn’t provide one) [Sinon.js]
    • Code coverage utility [Istanbul]
  • Linting
    • A linter with parser [ESlint]
    • A configuration to apply rules to your code

How to Test NodeJS Apps using Mocha, Chai and SinonJS

Unit 10: Application logging with Winston and Log4js

Application logging is a reality that we as developers have to deal with, and it isn’t going anywhere. When our applications run, things happen. Some of those things are important. Others are not.

Logs tell us what happened and are useful when supporting our applications. console.log() is fine for prototypes, but for production quality applications, you need production quality logging.

You can write this code yourself, but the logging problem has been solved.

Two popular third party logging packages for Node applications

Logging Example on GitHub: link

Unit 11: ExpressJS and Pug

  • ExpressJS: for a web framework, which includes routing.
  • Pug: for the user interface.

ExpressJS and Pug Example on GitHub: link

Unit 12: MongoDB

MongoDB is one of the most popular choices for storing data used with Node applications.

0%