Sam Portelance
Sam Portelance

DASHPORT is Deno’s first authentication middleware module for both the local login and OAuth 2.0 flows. Just like its Node.js predecessor, Passport, it’s lightweight, incredibly modular, and can be plugged into any Oak-based web app (with plans to accommodate more Deno middleware frameworks as competitors to Oak emerge). Dashport turns setting up authentication in your app from a project in-and-of itself to a single bullet point on your to-do list.

JUMP TO INSTALLATION INSTRUCTIONS

— — —

Before we begin, if you don’t already know about Deno, which Node.js creator Ryan Dahl developed as the sequel to Node, then this is your invitation to go learn about it!

Setting up a secure and simple login is an absolute necessity for user-facing web apps and because Deno is so new, there aren’t many great tools to assist in that fundamental process yet.

The Deno developer is faced with a couple options, to either carry out the challenging and hazardous chore of setting up a login and database that they’re confident won’t leave their user data vulnerable to attack or go through the arduous process of creating an OAuth 2.0 login flow manually.

There are four distinct main OAuth 2.0 flows. Dashport’s strategies employ the authorization code flow, so that’s the one we’ll be discussing, but if you’re interested in learning more you can do so here.

OAuth 2.0 is the industry standard authentication flow whereby a user grants a third party permission to use their pre-existing data on another site to log in with that third party. That’s a little opaque, so let’s look at this example from Spotify’s OAuth flow.

As you can see from the diagram, there are three entities at play: your app, your client, and your OAuth provider’s servers.

First, your app requests authorization from the user and the service provider prompts them to log in (if they’re not logged in already). Any scopes that you’re requesting access to are displayed so the user can see what they’re agreeing to share. If the user says no, you get an error message in response, if they accept, we move on to the next step.

Once your user has logged in, your app receives an authorization code which it uses to query another server in exchange for an access token. The access token is what will allow you to actually access the information you requested from your user.

Once you’ve received the token, you make a query to a different endpoint in exchange for the user information you requested.

This process can be involved, but Dashport automates all of it. All you have to do is add a strategy and call authenticate.

There’s debate as to whether OAuth is actually more secure and for good reason. For the average developer without a deep knowledge of cybersecurity, it’s almost definitely the way to go, but if you’re interested in the pros and cons please read on.

-OAuth lets the big boys handle security

The central premise of OAuth is that gaps in the security of information on the internet will be minimized if only those with the resources to do a cutting-edge-level good job are tasked with safeguarding user information. Whether or not you trust Google, Facebook, or LinkedIn to actually be responsible with user information is a different story, but if your user is logging through one of those services, they’ve already created an account with that company and and that means they’ve already made the decision to entrust them with their data for themselves.

-No new user data

Rather than forcing a user to create a new password, OAuth just verifies that a user is logged in somewhere else and reflects that verification in the form of some sort of userID, which wouldn’t be of much use to a hacker unless their goal was to see whether someone was logged into your site. However, OAuth 2.0 and Dashport can be used to access additional user information. Even in this case, that data already existed somewhere, your user isn’t being forced to put it out into the world for the first time.

-That data has to take a journey to get to you…

…and journeys often involve some risk. The user data is sent — either as a JSON, an xml-encoded URI, or in some other format through the URLs exchanged during the query requests. While these requests can only be accessed through your app, transmitting information always brings with it the inherent risk of exposure.

-Serialization

The user data you receive back is serialized using the algorithm you define so that the encryption can’t just be reverse-engineered by looking at Dashport’s publicly available source code. If you’d like to learn more about the sort of functions you can write to keep user data safe, you can read more, look into some modules that can serialize data for you, or check out some of the examples on Dashport’s site (just don’t copy them directly).

Whether you want to mitigate your own risk and adopt OAuth or set up a traditional login, Dashport is here to make your job easier.

Dashport is a distilled, automated login process that is modeled after Passport for Node. It can be plugged into your app, along with any of its sibling strategy modules, to decrease the amount of code that you have to write.

In an effort to stay true to Deno’s mission of not relying on modules that themselves rely on dozens of other modules, Dashport only lists Oak as a dependency, so it won’t make your app any more vulnerable to failure.

Dashport executes either the OAuth2.0 or local login flows (based on the strategy that you choose to authenticate with) and uses a serialize function that you define to safely store whatever data it recovers from your user. It then creates a session object to enable persistent logins.

If you want to dig into how those functions work, the app’s code can be found on Github, but if you’re just interested in the work that you have to do and not the work that’s already been done for you, keep reading!

First, require Dashport into your application’s server:

import Dashport from 'https://deno.land/x/dashport'

Then initialize Dashport, passing in the name of your application’s

middleware framework (currently Dashport only supports Oak):

const dashport = new Dashport('oak');

Next, add methods to serialize and deserialize whatever user data you collect:

dashport.addSerializer('serializer-1', (userInfo) => {const serializedId = Math.floor(Math.random() * 1000000000);userInfo.id = serializedId;try {const exampleUser = await exampleDbCreateUpsert(userInfo);return serializedId;} catch(err) {return err;}});dashport.addDeserializer('deserializer-1', (serializedId) => {try {const exampleUserInfo = await exampleDbFind({ id:         serializedId });return userInfo;} catch(err) {return err;}});

(we explain why this is necessary earlier in the article)

Next, require the strategies for whatever OAuth 2.0 service providers you want into your server (if you don’t see the provider you want to use, you can make your own strategy as well):

import GoogleStrategy from 'https://deno.land/x/dashport_google/mod.ts' 

Then add the strategies to the Dashport object you defined. AddStrategy requires two arguments, the name you’d like to use to refer to the strategy and an invocation of that strategy with all the fields it requires. This information will be used to get the access code and tokens from your OAuth service provider.

dashport.addStrategy('google', new GoogleStrategy({client_id: 'client-id-here',redirect_uri: 'redirect-uri-here',response_type: 'response-type-here',scope: 'scopes-wanted-here',client_secret: 'client-secret-here',grant_type: 'grant-type-here',}));

Now Dashport has everything it needs to work with your application! All you need to do now is call it. Add a call to Dashport.authenticate(<stratName>) with the name of the strategy that you defined during the setup in place of “<stratName>” (in this case it would be X) in the appropriate route.

router.get('/privatepage',dashport.authenticate('google'),async (ctx: any, next: any) => {ctx.body = 'This is a private page!';})

And that’s it! Whenever that route is called, Dashport will prompt your user to sign in with the service provider you specified, get their information, transform that information using the serializer you defined, and store it for you to access later using your deserializer function. Dashport will also create a session object for that user so that user so that next time they try to log in they’ll be routed straight to your protected page.

Dashport has additional methods for logging out and removing serializers and strategies, documentation for which can be found on their website.

Load More Related Articles
Load More By john
Load More In Javascript

Leave a Reply

Your email address will not be published. Required fields are marked *