Generate An Api Key Node.js

by Scott Domes

Node.js can be intimidating to beginners. But its flexible structure and lack of strict guidelines makes it seem more complicated than it is.

Mar 21, 2020  REST API generator with Node.js, Express and Mongoose - diegohaz/rest. REST API generator with Node.js, Express and Mongoose - diegohaz/rest. Set MASTERKEY=masterKey JWTSECRET=jwtSecret # commit and push the files git add -A git commit -m ' Initial commit ' git push heroku master # open the deployed app in the browser. Build a Shopify app with Node.js and Express In this tutorial you'll build a Node.js + Express application that connects to Shopify. Your application will authenticate with a shop, request a permanent access token, and then use that access token to make an API call. Feb 13, 2017  In IT consulting projects, we frequently have to use an existing database. Here’s how to create a simple REST API for a database in SQL Server using Node.js and the two modules Express (a Web.

API key generator for Node.js. Generate, authenticate, store and maintain keys for your RESTful API. This is a little tool for micro software vendors that need to create, authenticate, track and manage use of their APIs. Wow, we have created a simple API in node js. Now we have learned how to create a simple API but we have written our entire code inside the server.js file which will get messy if we are going to create Add More APIs in it. Jun 03, 2019  This will ensure anyone using this API key will not be able to, for example delete data from the database. We must now link this Role to an API key. If we now go to the Apps tab we can create a new API key with the corresponding Role. Once we hit save we are able to see the API key generated for our use.

This tutorial is a quick and simple guide to Node.js, the Express framework, and MongoDB, focusing on the fundamental REST routes and basic database interaction. You’ll build a simple API boilerplate that can then be used as the foundation for any app.

Who This Tutorial Is For: You should have a basic understanding of REST APIs and CRUD operations, plus basic JavaScript knowledge. I use ES6 (mainly fat-arrow functions), but nothing too complex.

For this tutorial, you’ll create the skeleton of a back-end for a note-taking application — think Google Keep. You want to be able to do all four CRUD actions on your notes: create, read, update, and delete.

Setting Up

If you don’t have Node installed, see here.

In a new directory, run npm init, and follow along with the prompts, giving your app the name of ‘notable’ (or whatever else you might like).

Once that’s done, you should have a package.json ready to go in your directory. This means you can start installing the dependencies you need for your project.

You’re going to use Express as your framework, MongoDB as the database, and a package called body-parser to help deal with JSON requests.

I also highly recommend installing Nodemon as a dev dependency. It’s a simple little package that automatically restarts your server when files change.

If you run:

You can then add the following script to package.json:

Your complete package.json should look like this:

Now you can create your server.js fileand start building your API.

Our Server

Let’s start by requiring all your dependencies in server.js.

You’re going to use the MongoClient to interact with your database. Note that you also initialize your app as an instance of Express, your framework.

The last thing you need to do to get your server up and running is to tell your app to start listening for HTTP requests.

You can specify a port, and start the listening like so:

Now if you run npm run dev (or node server.js if you didn’t install Nodemon) you should see ‘We are live on port 8000’ in the terminal.

Your server is live. But it doesn’t do a whole lot. Or anything, really.

Let’s fix that.

CRUDdy Routes

For this example, you want to build 4 routes; to CREATE a note, to READ your notes, to UPDATE a note, and to DELETE a note.

This will give you a good idea of how to structure almost any basic route with Node.

To test your API, though, you need to mimic a client side making requests. To do so, you’ll use a great app called Postman. It allows you to make simple HTTP requests with custom bodies and parameters.

Install Postman, and let’s start setting up your routes.

Super Organized

Most Node.js tutorials (and many real apps) put all their routes in one big routes.js file. This makes me a wee bit uncomfortable. In contrast, splitting up your files into separate folders leads to good readability, and makes big apps more manageable.

You don’t have a big app, but let’s do this right. Make the following directories: an app folder with a routes folder inside it, with an index.js and a note_routes.js file inside it.

In other words: root > app > routes > index.js and note_routes.js.

These directories may seem like overkill for your simple small app, but it’s always good to start with best practices.

Your First Route

Let’s start with the C in CRUD- create. How would you create a note?

Well, before you do that, you have to build a bit more infrastructure. In Express, routes are wrapped in a function, which takes the Express instance and a database as arguments.

Like this:

You can then export this function through your index.js:

Then import it for use in server.js:

Note that since you don’t have a database yet set up, you’re just passing in an empty object.

Okay, now you can make your CREATE route.

The syntax is simple:

When the app receives a post request to the ‘/notes’ path, it will execute the code inside the callback- passing in a request object (which contains the parameters or JSON of the request) and a response object (used to reply).

You can test this by using Postman to send a POST request to localhost:8000/notes.

Nice! You created your first real route.

Next step is to add some parameters to your request and process them in your API and, finally, add in your database.

Request Parameters

In Postman, go to the Body tab and add some key-value pairs, after selecting the x-www-form-urlencoded radio button.

This will add encoded form data to your request, which you’ll be able to process with your API.

Now in your note_routes.js, let’s just log out the body.

Try sending the Postman request and you’ll see… undefined.

Unfortunately, Express can’t process URL encoded forms on its own. But you did install that body-parser package…

Now you should see the body as an object in the terminal.

Last step to your preliminary route: set up the database, and then add your data in.

The easiest way to set up a Mongo database is through mLab: it’s free for the smallest size, and quite fast to setup.

Once you create an account and a MongoDB deployment, add a user to the database with a username and password:

then grab the URL here (the second one):

And in a directory config in the root of your project, create a db.js file.

Inside, add the URL:

Don’t forget to add your username and password (the ones from the database user, not your mLab account) into the URL. (If you’re committing this project to Github, be sure to include a .gitignore file like so, so you don’t share your password with everyone.)

Now in your server.js, you can use the MongoClient to connect to your DB, and use this to wrap your app setup:

If you’re using the latest version of the MongoDB (3.0+), modify it like so:

(Thanks to Alex Stroulger for the fix for 3.0)

That’s the last of your infrastructure setup! It’s all route-building from here.

Adding to your Database

MongoDB stores data in collections- which are exactly how they sound. In your case, you want to store your notes in a collection called — you guessed it — notes.

Since you pass in your database as the db argument in your routes, you can then access it like so:

Creating a note is as simple as calling insert on your collection:

Once the insert is complete (or has failed for whatever reason), you want to either send back an error or send back the newly created note object. Here’s the full note_routes.js:

Try it out! Send an x-www-form-urlencoded POST request with Postman, with a title and body set under the Body tab.

Api

The response should look like this:

If you log into mLab, you should also see the created note in the database.

Your READ Route

Now you can pick up the pace a bit.

Bucket policy generator arn no key name. For Role name, enter a name for the role.9.

Say you wanted to get back the note you just created, by navigating to localhost:8000/notes/{the id}. In this case, that would be localhost:8000/notes/585182bd42ac5b07a9755ea3.

(If you don’t have the ID for one of your notes, you can check on mLab or just create a new one).

Here’s what this would look like in note_routes.js:

Just like before, you’re going to call a method on your database collection of notes. Here, it’s the aptly named findOne.

You can grab the id from the URL parameters via req.params.id. However, if you try to just plop in the string into the <> above, it won’t work.

MongoDB requires not just an ID as a string, but as an ID object or, as they call it, an ObjectID.

Don’t worry, it’s an easy fix. Here’s the full code:

Try it out with one of your note ID’s, and it should look like this:

Your DELETE Route

Deleting an object is actually pretty much the same as finding an object. You just use the remove function instead of the findOne. Here’s the full code. I’ve highlighted what’s different from your GET:

Your UPDATE Route

Last one! The PUT is basically a hybrid between READ and CREATE. You find the object, then update it accordingly. If you deleted your only note, time to make another one!

The code:

Now you can update any of your notes, like so:

Note the imperfection with this code- if you fail to supply a body or title, the PUT request will nullify those fields on the note in the database.

You could easily add some conditional logic to update the fields only if they’re present in the request- I left that out just to keep it simple.

API Complete

That’s it! You have a working Node API with each of the four major CRUD operations.

The goal of this tutorial was to give you a degree of familiarity with Express, Node, and MongoDB — you can use your simple app as a launching pad for more complex projects.

In the future I’ll be writing tutorials to create more simple API’s in different languages and frameworks. Hit the follow button if you’re interested!

If this tutorial was any help to you, please hit the green heart below- it means a lot. Feel free to also leave me a comment with any feedback or questions.

Thanks for reading!

Have you ever wondered how authentication works? What’s behind all the complexity and abstractions. Actually, nothing special. It’s a way of encrypting a value, in turn creating a unique token that users use as an identifier. This token verifies your identity. It can authenticate who you are, and authorize various resources you have access to. If you by any chance don’t know any of these keywords, be patient, I’ll explain everything below.

This will be a step by step tutorial of how to add token based authentication to an existing REST API. The authentication strategy in question is JWT (JSON Web Token). If that doesn’t tell you much, it’s fine. It was just as strange for me when I first heard the term.

What does JWT actually mean in a down to earth point of view? Let’s break down what the official definition states:

JSON Web Token (JWT) is a compact, URL-safe means of representing claims to be transferred between two parties. The claims in a JWT are encoded as a JSON object that is used as the payload of a JSON Web Signature (JWS) structure or as the plaintext of a JSON Web Encryption (JWE) structure, enabling the claims to be digitally signed or integrity protected with a Message Authentication Code (MAC) and/or encrypted.
- Internet Engineering Task Force (IETF)

That was a mouthful. Let’s translate that to English. A JWT is an encoded string of characters which is safe to send between two computers if they both have HTTPS. The token represents a value that is accessible only by the computer that has access to the secret key with which it was encrypted. Simple enough, right?

What does this look like in real life? Let’s say a user wants to sign in to their account. They send a request with the required credentials such as email and password to the server. The server checks to see if the credentials are valid. If they are, the server creates a token using the desired payload and a secret key. This string of characters that results from the encryption is called a token. Then the server sends it back to the client. The client, in turn, saves the token to use it in every other request the user will send. The practice of adding a token to the request headers is as way of authorizing the user to access resources. This is a practical example of how JWT works.

Okay, that’s enough talk! The rest of this tutorial will be coding, and I’d love if you would follow along and code alongside me, as we progress. Every snippet of code will be followed by an explanation. I believe the best way of understanding it correctly will be to code it yourself along the way.

Before I begin, there are some things you need to know about Node.js and some EcmaScript standards I’ll be using. I will not be using ES6, as it is not as beginner friendly as traditional JavaScript. But, I will expect you already know how to build a RESTful API with Node.js. If not, you can take a detour and check this out before proceeding.

Also, the whole demo is on GitHub if you wish to see it in its entirety.

Let’s start writing some code, shall we?

Well, not yet actually. We need to set up the environment first. The code will have to wait at least a couple more minutes. This part is boring so to get up and running quick we’ll clone the repository from the tutorial above. Open up a terminal window or command line prompt and run this command:

You’ll see a folder appear, open it up. Let’s take a look at the folder structure.

We have a user folder with a model and a controller, and basic CRUD already implemented. Our app.js contains the basic configuration. The db.js makes sure the application connects to the database. The server.js makes sure our server spins up.

Go ahead and install all required Node modules. Switch back to your terminal window. Make sure you’re in the folder named nodejs-restful-api and run npm install. Wait a second or two for the modules to install. Now you need to add a database connection string in db.js.

Jump over to mLab, create an account if you do not already have one, and open up your database dashboard. Create a new database, name it as you wish and proceed to its configuration page. Add a database user to your database and copy the connection string from the dashboard to your code.

All you need to do now is to change the placeholder values for <dbuser> and <dbpassword>. Replace them with the username and password of the user you created for the database. A detailed step by step explanation of this process can be found in the tutorial linked above.

Let’s say the user I created for the database is named wally with a password of theflashisawesome. Having that in mind, the db.js file should now look something like this:

Go ahead and spin up the server, back in your terminal window type node server.js. You should see Express server listening on port 3000 get logged to the terminal.

Finally, some code.

Let’s start out by brainstorming about what we want to build. First of all we want to add user authentication. Meaning, implementing a system for registering and logging users in.

Secondly, we want to add authorization. The act of granting users the permission to access certain resources on our REST API.

Start out by adding a new file in the root directory of the project. Give it a name of config.js. Here you’ll put configuration settings for the application. Everything we need at the moment is just to define a secret key for our JSON Web Token.

Disclaimer: Have in mind, under no circumstances should you ever, (EVER!) have your secret key publicly visible like this. Always put all of your keys in environment variables! I’m only writing it like this for demo purposes.

Node.js Generate Api Key

With this added you’re ready to start adding the authentication logic. Create a folder named auth and start out by adding a file named AuthController.js. This controller will be home for our authentication logic.

Add this piece of code to the top of the AuthController.js.

Now you’re ready to add the modules for using JSON Web Tokens and encrypting passwords. Paste this code into the AuthController.js:

Open up a terminal window in your project folder and install the following modules:

That’s all the modules we need to implement our desired authentication. Now you’re ready to create a /register endpoint. Add this piece of code to your AuthController.js:

Here we’re expecting the user to send us three values, a name, an email and a password. We’re immediately going to take the password and encrypt it with Bcrypt’s hashing method. Then take the hashed password, include name and email and create a new user. After the user has been successfully created, we’re at ease to create a token for that user.

The jwt.sign() method takes a payload and the secret key defined in config.js as parameters. It creates a unique string of characters representing the payload. In our case, the payload is an object containing only the id of the user. Let’s write a piece of code to get the user id based on the token we got back from the register endpoint.

Here we’re expecting the token be sent along with the request in the headers. The default name for a token in the headers of an HTTP request is x-access-token. If there is no token provided with the request the server sends back an error. To be more precise, an 401 unauthorized status with a response message of No token provided. If the token exists, the jwt.verify() method will be called. This method decodes the token making it possible to view the original payload. We’ll handle errors if there are any and if there are not, send back the decoded value as the response.

Finally we need to add the route to the AuthController.js in our main app.js file. First export the router from AuthController.js:

Then add a reference to the controller in the main app, right above where you exported the app.

Let’s test this out. Why not?

Open up your REST API testing tool of choice, I use Postman or Insomnia, but any will do.

Go back to your terminal and run node server.js. If it is running, stop it, save all changes to you files, and run node server.js again.

Open up Postman and hit the register endpoint (/api/auth/register). Make sure to pick the POST method and x-www-form-url-encoded. Now, add some values. My user’s name is Mike and his password is ‘thisisasecretpassword’. That’s not the best password I’ve ever seen, to be honest, but it’ll do. Hit send!

See the response? The token is a long jumbled string. To try out the /api/auth/me endpoint, first copy the token. Change the URL to /me instead of /register, and the method to GET. Now you can add the token to the request header.

Voilà! The token has been decoded into an object with an id field. Want to make sure that the id really belongs to Mike, the user we just created? Sure you do. Jump back into your code editor.

Now when you send a request to the /me endpoint you’ll see:

The response now contains the whole user object! Cool! But, not good. The password should never be returned with the other data about the user. Let’s fix this. We can add a projection to the query and omit the password. Like this:

That’s better, now we can see all values except the password. Mike’s looking good.

Api Key Generator

Did someone say login?

After implementing the registration, we should create a way for existing users to log in. Let’s think about it for a second. The register endpoint required us to create a user, hash a password, and issue a token. What will the login endpoint need us to implement? It should check if a user with the given email exists at all. But also check if the provided password matches the hashed password in the database. Only then will we want to issue a token. Add this to your AuthController.js.

First of all we check if the user exists. Then using Bcrypt’s .compareSync() method we compare the password sent with the request to the password in the database. If they match we .sign() a token. That’s pretty much it. Let’s try it out.

Cool it works! What if we get the password wrong?

Great, when the password is wrong the server sends a response status of 401 unauthorized. Just what we wanted!

To finish off this part of the tutorial, let’s add a simple logout endpoint to nullify the token.

Disclaimer: The logout endpoint is not needed. The act of logging out can solely be done through the client side. A token is usually kept in a cookie or the browser’s localstorage. Logging out is as simple as destroying the token on the client. This /logout endpoint is created to logically depict what happens when you log out. The token gets set to null.

With this we’ve finished the authentication part of the tutorial. Want to move on to the authorization? I bet you do.

Build Restful Api Node Js

Do you have permission to be here?

To comprehend the logic behind an authorization strategy we need to wrap our head around something called middleware. Its name is self explanatory, to some extent, isn’t it? Middleware is a piece of code, a function in Node.js, that acts as a bridge between some parts of your code.

When a request reaches an endpoint, the router has an option to pass the request on to the next middleware function in line. Emphasis on the word next! Because that’s exactly what the name of the function is! Let’s see an example. Comment out the line where you send back the user as a response. Add a next(user) right underneath.

Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
- Using middleware, expressjs.com

Jump back to postman and check out what happens when you hit the /api/auth/me endpoint. Does it surprise you that the outcome is exactly the same? It should be!

Disclaimer: Go ahead and delete this sample before we continue as it is only used for demonstrating the logic of using next().

Let’s take this same logic and apply it to create a middleware function to check the validity of tokens. Create a new file in the auth folder and name it VerifyToken.js. Paste this snippet of code in there.

Let’s break it down. We’re going to use this function as a custom middleware to check if a token exists and whether it is valid. After validating it, we add the decoded.id value to the request (req) variable. We now have access to it in the next function in line in the request-response cycle. Calling next() will make sure flow will continue to the next function waiting in line. In the end, we export the function.

Now, open up the AuthController.js once again. Add a reference to VerifyToken.js at the top of the file and edit the /me endpoint. It should now look like this:

See how we added VerifyToken in the chain of functions? We now handle all the authorization in the middleware. This frees up all the space in the callback to only handle the logic we need. This is an awesome example of how to write DRY code. Now, every time you need to authorize a user you can add this middleware function to the chain. Test it in Postman again, to make sure it still works like it should.

Feel free to mess with the token and try the endpoint again. With an invalid token, you’ll see the desired error message, and be sure the code you wrote works the way you want.

Why is this so powerful? You can now add the VerifyTokenmiddleware to any chain of functions and be sure the endpoints are secured. Only users with verified tokens can access the resources!

Wrapping your head around everything.

Don’t feel bad if you did not grasp everything at once. Some of these concepts are hard to understand. It’s fine to take a step back and rest your brain before trying again. That’s why I recommend you go through the code by yourself and try your best to get it to work.

Again, here’s the GitHub repository. You can catch up on any things you may have missed, or just get a better look at the code if you get stuck.

Remember, authentication is the act of logging a user in. Authorization is the act of verifying the access rights of a user to interact with a resource.

Middleware functions are used as bridges between some pieces of code. When used in the function chain of an endpoint they can be incredibly useful in authorization and error handling.

Hope you guys and girls enjoyed reading this as much as I enjoyed writing it. Until next time, be curious and have fun.

Node Js Generate Uuid

Do you think this tutorial will be of help to someone? Do not hesitate to share. If you liked it, please clap for me.