The Best Security for Single Page Applications(SPA) - OpenID Connect OAuth 2.0 Authorization Code PKCE Flow
Tags: openidconnect, appauth, angular, react
Published: 2020-08-07 12:27:23

---
title: The Best Security for Single Page Applications(SPA) - OpenID Connect OAuth 2.0 Authorization Code PKCE Flow
published: true
description: OpenID Connect OAuth 2.0 Authorization Code PKCE Flow is the best OpenID Connect security flow for Single Page Applications. Where you don't need to expose access token in browser URL.
tags: #openidconnect #appauth #angular #react
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/jq9v159js8sxwtf5noa6.jpg

---

The user identity and data security is a crucial part of your application. Your application should need to be 100% sure that the one who is using the application is the correct user. The only username/password security to identify users and for application security is a bad idea :thumbsdown: .

### What is OpenID Connect OAuth 2.0?

:dart: `OpenID Connect OAuth 2.0` is the best security framework available nowadays. 

You must have seen in so many applications that **log in with Twitter, Gmail, Facebook**. So Once we click on a button it redirects us to specific social media(OP - OpenID Connect Server). We login to social media, redirect back to the current application and the current application allows us to log in. So How can social media platform allows the other application to authenticate and authorized user so This is OpenID Connect OAuth 2.0 security. 

[More Details](https://openid.net/connect/)

Instead of building your own just username/password security, you should have to integrate implement or integrate OpenID Connect OAuth 2.0 security.

There are many security flows available in OpenID Connect OAuth 2.0. As per your Application requirements and flow, you can choose the flow.

There are three flow for **Single Page Application(SPA)**.
1. Implicit flow
2. Authorization Code Flow (without PKCE) - This is not really for SPA Applications
3. Authorization Code PKCE Flow

## :x: Why not **implicit flow**?
Because it exposes access_token into the browser URL and you will not have **refresh_token** facility because OP client is not able to call **/token** endpoint which requires client authentication.

Below is the implicit flow diagram which helps you to understand the whole flow.

> Note: server.com and client.com are just for example. You need to use endpoints as per your OpenID Providers.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/k7aly1bl3t37w1qgejhk.png)

## :x: Why not **Authorization Code Flow (without PKCE)** for SPA?

Stop.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/k4ue3k96dgc3xsodzca7.gif)

Don't use it. Without PKCE that means You need to store the client secret on your browser to request **/token** endpoint and get an access token. Store client secret at the browser is a big security risk.

This flow is generally used at the server-side. Where we can safely store client id and client secret. In this case, the **/token** endpoint is protected by [**Token Endpoint authentication methods**](http://webconcepts.info/concepts/oauth-token-endpoint-auth-method/). :heavy_check_mark: You don't need PKCE flow if you are managing authentication flow using the server.

## :heavy_check_mark: Why to use **Authorization Code PKCE flow.**?
:heart: If you have a SPA(Single Page Application), the best security flow for this is the **Authorization Code with PKCE flow.** Because It **does not expose access token** to the browser in URL and you **don't need client secret** at all.

PKCE stands for **Proof Key for Code Exchange**.

In this case, the **/token** endpoint is not protected by [**Token Endpoint authentication methods**](http://webconcepts.info/concepts/oauth-token-endpoint-auth-method/). Because of PCKE, OP Server use **code_challenge** and **code_verifier** to verify request. You also need to check what should be the token endpoint auth method for PKCE flow. This is vary as per oidc service provider.

## :heavy_check_mark: Authorization Code PKCE flow and implementation


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zgds6m0n0ykpq30oihlb.png)

> Note: server.com and client.com are just for example. You need to use endpoints as per your OpenID Connect Providers.

1.First, you need to **code_verifier** and **code_challenge**. Below is the code of Node.js to generate **code_challenge**. **code_verifier** is just a random string.

```javascript
var code_verifier="s4vqXQA0ePi98eS9Px4jcghBi7UQHRaQl6jMRwLkBj9Eh8g1yxnesereK4jUHdAT0HkLEWBPLZ8z35HX1Ditxf"

const crypto = require('crypto')
const base64url = require('base64url')

var hash = crypto.createHash('sha256').update(code_verifier).digest();
var code_challenge = base64url.encode(hash)
console.log(code_challenge)
```

This is a simple Node.js code. For SPA applications, there is the best library available that is [AppAuth JS](https://github.com/openid/AppAuth-JS). I've a integrate it with Angular and React Please check links

{% github kdhttps/appauth-angular %}

{% github kdhttps/appauth-react %}

2.Authorization request to OP Server

```sh
HTTP Get redirect

https://server.com/authorize
?redirect_uri=https://client.com/callback
&client_id=[your_client_id]
&response_type=code
&state=[uuid]
&scope=openid%20email%20profile
&code_challenge=[code_challenge]
&code_challenge_method=S256
```

3.OP Server authenticates the user and redirects back to `https://client.com/callback` with code in URL. You can check the above flow diagram.

4.Now request to **https://server.com/token** with **code** and **code_challenge**.

```sh
HTTP POST https://server.com/token
content-type: application/x-www-form-urlencoded
accept: application/json

Form Data:
grant_type: authorization_code
client_id: [your_client_id]
redirect_uri: [your_callback_url]
code: [code]
code_verifier: [code_verifier]
```

This request will return your JSON response with **access_token** 

5.Request to **https://server.com/usernifo** endpoint with **access_token** and get user info. 

I am not forcing you to use PKCE flow but it is better than the implicit flow.

I've integrated the Authorization Code PKCE flow in my Angular and React App. Code links are given below:

{% github kdhttps/appauth-angular no-readme %}

{% github kdhttps/appauth-react no-readme %}

I've one application on Heroku. If you want to check then click here [https://mean-star.herokuapp.com/](https://mean-star.herokuapp.com)

I am using [auth0.com](auth0.com) as my OpenID Connect Server. You can use any provider which provides you OpenID Connect Standards. I would like to list here some: [Janssen Project Auth Server](jans.io), [Gluu Server](gluu.org), Auth0, Okta, KeyCloak. Please comment if you have more OpenID Connect Providers

You can also use Google, Twitter, Facebook who provide this feature.

Happy Helping :blush:, Thank you !!!

[For More Blog](https://kdhttps.com)