Browser Extension with OAuth 2.0 Authorization
Tags: extension, oauth, authorization, chrome
Published: 2020-05-11 18:47:46

It's not every day that you have to develop Browser Extensions and that too with the integration of OAuth 2.0 Authorization.

`" OAuth is an open protocol to allow secure authorization in a simple and standard method from web, mobile and desktop applications. "`

Basically, OAuth provides a standard procedure through which Developers can get their third party apps authenticated through OAuth providers without handling any user auth info. It's a pretty simple and easy to implement procedure but can easily get complicated if the documentation provided by the Oauth Provider is not clear or if the developer is a newbie like me.

> **Note:** This post can be helpful for anyone who is facing any problem regarding the implementation of OAuth procedure.

##How to do it
For this procedure we are going to use a library called [ChromeAuth2](https://github.com/whoisjuan/ChromeAuth2)

![ChromeAuth2](https://dev-to-uploads.s3.amazonaws.com/i/brsm3bw70kmjqgc3dh9m.png)

####1. Create your work directory with somewhat similar structure
![Directory Structure](https://dev-to-uploads.s3.amazonaws.com/i/qxnc7ymg5owhn5ku3nrg.png)

Here:
- **assets**: Contains all your images, styles and scripts
- **libs**  : Contains all your libraries
- **pages** : Contains all other `.html` files
- **icon_128.png** : icon for chrome store
- **icon.png** : icon for toolbar
- **manifest.json** : Settings for the extension
- **popup.html** : main file of the extension



####2. Add the following to your `manifest.json`
```json
{
	"manifest_version": 2,
	"name": "Extension Name",
	"description": "Extension's Description",
	"version": "1.0.0",
	"icons": { "128": "icon_128.png" },
	"browser_action": {
		"default_icon": "icon.png",
		"default_popup": "./popup.html"
	},
	"permissions": [
		"your OAuth provider's token API",
		"tabs",
		"storage"
	],

	"content_scripts": [
		{
			"matches": ["https://redirect-ing.web.app/*"],
			"js": ["libs/chrome-ex-oauth2/injection.js"],
			"run_at": "document_start"
		}
	],
	"web_accessible_resources": ["libs/*"]
}
```
> **Note:** Replace the first string in the permission's array with the access token's api provided to you by your OAuth provider, you don't need to change anything other than that.

####3. Add your application and API provider information to `libs/chrome-ex-auth/oauth2.js`:
```js
(function() {
		window.oauth2 = {
		
		access_token_url: "{your-access-token-url}",
		authorization_url: "{your-authorization-url}",
		client_id: "{your-client-id}",
		client_secret: "{your-client-secret}",
		redirect_url: "{your-redirect-url}",
		scopes: [{your-array-of-scopes}],
		
		...
		...
	
	})();	
```
> **Note:** The provided function is only a boiler-plate. The variable names and the variables you pass to the Authorization API would be specific to your API provider. Some authorization APIs would require other parameters like `scope` and `response-type`.

> You would need to include those parameters in your initial variables and modify the `start()` function to include the newly added parameters. You might also need to add some logic if you have an array of scopes or other array of values that need to be passed to the URL:

```js
start: function() {
		    window.close();
		    // Modify this url depending on the parameters that your API providers requires you to pass.
		    var url = this.authorization_url + "?client_id=" + this.client_id + "&redirect_uri=" + this.redirect_url + "&response_type=" + this.response_type + "&scope=" + this.scope;
		    // Use this logic to include several scopes.
		    // for(var i in this.scopes) {
		    //     url += this.scopes[i];
		    // }
		    chrome.tabs.create({ url: url, active: true });
		},
```


####4. Include the script to your `popup.html` and invoke the authorization
include the following script in your head tag:
```html
<html>
  <head>
    <script src="./libs/chrome-ex-oauth/oauth2.js" defer></script>
    <script src="./assets/js/app.js" defer></script>
  <head>
  <body>
    ...
    <button id="authorize">Authorize</button>
    ...
  </body>
</html>

```
And, invoke the function from `assets/js/app.js`:
```js
document.querySelector("#authorize").addEventListener("click", () => {
  window.oauth2.start();
});
```

Now you can upload the extension to Chrome and test it out.