Dashport: A Login Solution for Deno

Sam Portelance
Feb 25 · 6 min read

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.

WHAT IS OAUTH 2.0

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.

THE OVER/UNDER ON OAUTH

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).

HELP IS HERE

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.

HOW IT WORKS

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!

HOW TO SET IT UP

(Note: this is an abridged tutorial for quick set up. If you’d like to see how to do all this setup in a separate file, please see their README.)

First, import Dashport into your application’s server:

import DashportOak from 'https://deno.land/x/dashport/mod.ts';

(Currently, Dashport only supports Oak but additional framework releases are planned and those versions will have the same nomenclature — e.g. “DashportExpress” .)

Next, instantiate Dashport, passing in the instantiation of your framework (in this case Oak — you need to do this so Dashport can call app.use() on itself under the hood):

import { Application } from "https://deno.land/x/oak/mod.ts";const app = new Application();
const dashport = new DashportOak(app);

Then, import and instantiate the strategies for whatever OAuth 2.0 service providers you want into your server:

import GoogleStrategy from 'https://deno.land/x/dashport_google/mod.ts' const googStrat = new GoogleStrategy({
client_id: 'client-id-here',
client_secret: 'client-secret-here',
redirect_uri: 'http://localhost:8000/privatepage',
response_type: 'code',
scope: 'profile email openid',
grant_type: 'authorization_code',
});

Then define methods to serialize and deserialize the information returned from your OAuth service provider (I explain why this is necessary earlier in the article):

const serializer = async (userInfo: any) => {
const serializedId = Math.floor(Math.random() * 1000000000);
userInfo.id = serializedId;

try {
await exampleDbCreateUpsert(userInfo);
return serializedId;
} catch(err) {
return err;
// or return new Error(err);
}
};
const deserializer = async (serializedId: (string | number)) => {
try {
const userInfo = await exampleDbFind({ id: serializedId });
return userInfo;
} catch(err) {
return err;
// or return new Error(err);
}
};

and just like that you’re ready to authenticate users!

HOW TO USE IT

Now Dashport has everything it needs to work with your application. All you need to do now is to add a call to Dashport.authenticate with your strategy and serializer/deserializer functions passed in as arguments.

router.get('/privatepage', 
dashport.authenticate(googStrat, serializer, deserializer),
async (ctx: any, next: any) => {
ctx.response.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 in ctx.locals. 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.

The Startup

Get smarter at building your thing. Join The Startup’s +788K followers.

Sign up for Top 10 Stories

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +788K followers.

Sam Portelance

Written by

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +788K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store