Sean Robertson

Sean Robertson

1567242805

Authenticate a Node ES6 API with JSON Web Tokens

In this guide, we’ll be implementing token based authentication in our own node.js API using JSON web tokens.

Table of Contents

  • Plan of attack
  • Setup
  • Environment variables
  • Server initialization
  • Developing our add user functionality
  • Route setup
  • Developing the User Model
  • Hashing users passwords
  • Developing our log in user functionality
  • Express middleware
  • Conclusion

Plan of attack

We’ll begin by:

  1. Setting up our development environment and initializing our express server.
  2. Creating our first basic route and controller.
  3. Fleshing out our routes and controllers to add users and login users.
  4. Creating a route and controller that will handle getting all users.

Finally, we’ll

  1. Setting up our development environment and initializing our express server.
  2. Creating our first basic route and controller.
  3. Fleshing out our routes and controllers to add users and login users.
  4. Creating a route and controller that will handle getting all users.

Sounds exciting? Let’s get to it then.

Setup

Before we get started in earnest, we’ll need to have a few things taken care of.

Folder structure

Here’s what our folder structure will look like:

├── config.js
├── controllers
│   └── users.js
├── index.js
├── models
│   └── users.js
├── routes
│   ├── index.js
│   └── users.js
├── utils.js

Quickly create it using the following commands:

>> mkdir -p jwt-node-auth/{controllers/users.js,models/users.js,routes/index.js,routes/users.js}
>> cd jwt-node-auth
>> touch utils.js && touch config.js && touch index.js

Prerequisites & Dependencies

The only global install we’ll need is node.js so make sure you have that installed. After that, let’s install our local project dependencies.

Run the following command to initialize our package.json file.

npm init --yes

Install all our dependencies by running:

>> npm install express body-parser bcrypt dotenv jsonwebtoken mongoose  --save
>> npm install morgan nodemon cross-env  --save-dev

Why these dependencies?

Dependencies
  1. Setting up our development environment and initializing our express server.
  2. Creating our first basic route and controller.
  3. Fleshing out our routes and controllers to add users and login users.
  4. Creating a route and controller that will handle getting all users.

Development dependencies

  1. Setting up our development environment and initializing our express server.
  2. Creating our first basic route and controller.
  3. Fleshing out our routes and controllers to add users and login users.
  4. Creating a route and controller that will handle getting all users.

Environment variables

Here’s what my .env file looks like. As an example, wherever in our code you see, MONGO_LOCAL_CONN_URL we’re referencing the value after the = sign in our .env file. The same applies to JWT_SECRET and MONGO_DB_NAME

JWT_SECRET=addjsonwebtokensecretherelikeQuiscustodietipsoscustodes
MONGO_LOCAL_CONN_URL=mongodb://127.0.0.1:27017/node-jwt
MONGO_DB_NAME=auth-with-jwts

Server initialization

Now, let’s set up our server.

Add the following line to your package.json file.

package.json

Inside the already existing scripts object, add the dev key value pair.

"scripts": {
    "dev": "cross-env NODE_ENV=development nodemon index.js"
  },

We’ll now start our server with the npm run dev command.

Every time we do this, development is automatically set as a value for the NODE_ENV key in our process object. The command nodemon index.js will allow nodemon to restart our server every time we make changes in our folder structure.

Let’s define the port we’ll have our server listen to in the config file.

config.js

module.exports = {
  development: {
    port: process.env.PORT || 3000
  }
}

Then set up our server like this:

index.js

require('dotenv').config(); // Sets up dotenv as soon as our application starts

const express = require('express'); 
const logger = require('morgan');
const bodyParser = require('body-parser');

const app = express();
const router = express.Router();

const environment = process.env.NODE_ENV; // development
const stage = require('./config')[environment];

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

if (environment !== 'production') {
  app.use(logger('dev'));
}

app.use('/api/v1', (req, res, next) => {
  res.send('Hello');
  next();
});

app.listen(`${stage.port}`, () => {
  console.log(`Server now listening at localhost:${stage.port}`);
});

module.exports = app;

Navigate to your terminal and run the command npm run dev at the root of the jwt-node-auth folder and make sure the word Hello is logged when you access the uri localhost:3000/api/v1 on your browser.

Now that we’re all set up, let’s move on to bootstrapping our add user functionality.

Developing our add user functionality

Let’s modify our server to accept our routing function as middleware that will be triggered on all our routes.

Add the following lines in index.js and **controllers/users.js **.

index.js

const routes = require('./routes/index.js');

app.use('/api/v1', routes(router));

Notice that we’ve modified the line app.use('/api/v1', (req, res, next) => {....} to the one above.

controllers/users.js

module.exports = {
  add: (req, res) => {
    return;
  }
}

Route setup

routes/index.js

const users = require('./users');

module.exports = (router) => {
  users(router);
  return router;
};

Here, to keep our code clean, we pass our main router from our index.js file to the users router in routes/users.js, which will handle all functionality related to our users.

routes/users.js

const controller = require('../controllers/users');

module.exports = (router) => {
  router.route('/users')
    .post(controller.add);
};

All we’re doing here is passing our add controller to our router. It’ll be triggered when we make a POST request to the /users route.

Next, let’s work on defining our users model.

Developing the User Model

models/users.js

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

const environment = process.env.NODE_ENV;
const stage = require('./config')[environment];

// schema maps to a collection
const Schema = mongoose.Schema;

const userSchema = new Schema({
  name: {
    type: 'String',
    required: true,
    trim: true,
    unique: true
  },
  password: {
    type: 'String',
    required: true,
    trim: true
  }
});

module.exports = mongoose.model('User', userSchema);

To add users to our collection, we’ll require that they give us a name and password string.

Hashing users passwords

As stated before, we’ll use bcrypt to hash our users passwords before we store them.

Let’s add a line to our config file to specify how many times we want to salt our passwords.

config.js

 module.exports = {
  development: {
    port: process.env.PORT || 3000,
    saltingRounds: 10
  }
}

We’ll use the mongoose pre hook on save to make sure our passwords are hashed before we save them. Add the following above the module.exports = mongoose.model('User', userSchema); line.

models/users.js

// encrypt password before save
userSchema.pre('save', function(next) {
  const user = this;
  if(!user.isModified || !user.isNew) { // don't rehash if it's an old user
    next();
  } else {
    bcrypt.hash(user.password, stage.saltingRounds, function(err, hash) {
      if (err) {
        console.log('Error hashing password for user', user.name);
        next(err);
      } else {
        user.password = hash;
        next();
      }
    });
  }
});

Now, let’s modify our add users controller to handle adding users after being handed a name and password

controllers/users.js

const mongoose = require('mongoose');
const User = require('../models/users');

const connUri = process.env.MONGO_LOCAL_CONN_URL;

module.exports = {
  add: (req, res) => {
    mongoose.connect(connUri, { useNewUrlParser : true }, (err) => {
      let result = {};
      let status = 201;
      if (!err) {
        const { name, password } = req.body;
        const user = new User({ name, password }); // document = instance of a model
        // TODO: We can hash the password here before we insert instead of in the model
        user.save((err, user) => {
          if (!err) {
            result.status = status;
            result.result = user;
          } else {
            status = 500;
            result.status = status;
            result.error = err;
          }
          res.status(status).send(result);
        });
      } else {
        status = 500;
        result.status = status;
        result.error = err;
        res.status(status).send(result);
      }
    });
  },
}

In the above code, we connect to our mongodb database then access the name and password provided in the request by destructuring those properties from the request.body object. Remember, we can do this because of our bodyparser middleware.

Next we create a new user document by calling new on our model then in the same step add the name and password we got from the request to the new document.

We could easily have done this instead.

const name = req.body.name;
const password = req.body.password;

let user = new User();
user.name = name;
user.password = password;

user.save((err, user) => { ... }

Does that seem clearer?

We exploited mongoose’s pre hook and hashed our password in our users model but we could just as well have hashed it in our controller before we called user.save

Finally, we pass a callback function into user.save that will handle our errors and pass the user back to us in our server response. We attach a handy status property in our response to let us know if the result was successful or not.

Testing with Postman

I’m using Postman to test out my API functionality but you can use any request library or application you like. Heck, you can even use curl if you’re a console purist. Cue the XBox and Playstation fan boys and fan girls. Tada!

As you can see below, we can now create users by making POST requests to the /api/v1/users endpoint.

What’s that strange string as the value under the password key? Well, that’s our password in hash form. We store it this way because it’s safer. Hashes are ridiculously difficult to reverse.

Edit out the pre save hashing hook and see what happens. Don’t forget to put it back though. Perish the thought!

We’ll see how to verify that a user is who they say they are, using the password they give us later when we work on the /login route.

Here’s what happens when we try to create a user without specifying a password.

Here’s what happens when we try to duplicate a user.

Developing our log in user functionality

routes/users.js

const controller = require('../controllers/users');

module.exports = (router) => {
  router.route('/users')
    .post(controller.add);

  router.route('/login')
    .post(controller.login)
};

Add the following import statement to the users controller.

const bcrypt = require('bcrypt');

Then, let’s add the login controller that will handle our requests to the /login route.

login: (req, res) => {
    const { name, password } = req.body;

    mongoose.connect(connUri, { useNewUrlParser: true }, (err) => {
      let result = {};
      let status = 200;
      if(!err) {
        User.findOne({name}, (err, user) => {
          if (!err && user) {
            // We could compare passwords in our model instead of below
            bcrypt.compare(password, user.password).then(match => {
              if (match) {
                result.status = status;
                result.result = user;
              } else {
                status = 401;
                result.status = status;
                result.error = 'Authentication error';
              }
              res.status(status).send(result);
            }).catch(err => {
              status = 500;
              result.status = status;
              result.error = err;
              res.status(status).send(result);
            });
          } else {
            status = 404;
            result.status = status;
            result.error = err;
            res.status(status).send(result);
          }
        });
      } else {
        status = 500;
        result.status = status;
        result.error = err;
        res.status(status).send(result);
      }
    });
  }

Above, we query our collection to find the user by their name. If we find them, we use bcrypt to compare the hash generated using the password they’ve given us and the hash that we’d previously stored. If we don’t find them, we send ourselves an error.

As you can see above, we can now log in our users. As an experiment, try logging in a user without a password or with an incorrect password and see what happens.

Adding Tokens to our authentication process

Let’s add the following import statement to our users controller then work on modifying our login controller to create tokens.

As mentioned before, we’ll use these to protect one of our routes from unauthorized access.

controllers/users.js

const jwt = require('jsonwebtoken');
login: (req, res) => {
    const { name, password } = req.body;

    mongoose.connect(connUri, { useNewUrlParser: true }, (err) => {
      let result = {};
      let status = 200;
      if(!err) {
        User.findOne({name}, (err, user) => {
          if (!err && user) {
            // We could compare passwords in our model instead of below as well
            bcrypt.compare(password, user.password).then(match => {
              if (match) {
                status = 200;
                // Create a token
                const payload = { user: user.name };
                const options = { expiresIn: '2d', issuer: 'https://scotch.io' };
                const secret = process.env.JWT_SECRET;
                const token = jwt.sign(payload, secret, options);

                // console.log('TOKEN', token);
                result.token = token;
                result.status = status;
                result.result = user;
              } else {
                status = 401;
                result.status = status;
                result.error = `Authentication error`;
              }
              res.status(status).send(result);
            }).catch(err => {
              status = 500;
              result.status = status;
              result.error = err;
              res.status(status).send(result);
            });
          } else {
            status = 404;
            result.status = status;
            result.error = err;
            res.status(status).send(result);
          }
        });
      } else {
        status = 500;
        result.status = status;
        result.error = err;
        res.status(status).send(result);
      }
    });
  }

Once we verify that a user is who they say they are, we create a token and pass it to our server response. If something goes wrong, we pass back an error as the response.

Now, we get a token every time we successfully log in a user. Yaaay!

Express middleware

An express middleware function is a function that gets triggered when a route pattern is matched in our request uri. All middleware have access to the request and response objects and can call the next()function to pass execution onto the subsequent middleware function.
Believe it or not, we’ve written out several already. Don’t believe me? I’ll show you.

Bodyparser and morgan are both middleware that act on all our routes. When we call the app.use function without the specifying the first parameter, we’re esentially doing this:

app.use(bodyParser.json()); 
// This is equivalent to
app.use('/', bodyParser.json());

if (environment !== 'production') {
  app.use(logger('dev'));
  // and this
  app.use('/', logger('dev'));
}

// Here, we've specified the pattern we'd like to be matched from our request's uri
app.use('/api/v1', (req, res, next) => {
  res.send('Hello');
  // We call next to hand execution over to the next middleware
  next();
});

Hold that thought and for now, let’s create a controller function that will get all users from our users collection.

controllers/users.js

getAll: (req, res) => {
    mongoose.connect(connUri, { useNewUrlParser: true }, (err) => {
      User.find({}, (err, users) => {
        if (!err) {
          res.send(users);
        } else {
          console.log('Error', err);
        }
      });
    });
  }

Add our new controller to our routing function.

routes/users.js

const controller = require('../controllers/users');

module.exports = (router) => {
  router.route('/users')
    .post(controller.add)
    .get(controller.getAll); // This route will be protected shortly

  router.route('/login')
    .post(controller.login);
};

Have you noticed that our controllers are esentially middleware functions passed to our other routing middleware? Above we’ve just added middleware our controller that will handle GET requests made to /users. However, we haven’t protected our route yet.

If we make a GET request to /users, here’s what happens.

But we wouldn’t want just any user to access a list of all our users. So, let’s create an admin user then check if they have a token before we allow access to this functionality.

Now, finally, let’s write out middleware to validate that a user has a valid token (issued by us and not expired) before we allow access to certain routes on our application.

utils.js

const jwt = require('jsonwebtoken');

module.exports = {
  validateToken: (req, res, next) => {
    const authorizationHeaader = req.headers.authorization;
    let result;
    if (authorizationHeaader) {
      const token = req.headers.authorization.split(' ')[1]; // Bearer <token>
      const options = {
        expiresIn: '2d',
        issuer: 'https://scotch.io'
      };
      try {
        // verify makes sure that the token hasn't expired and has been issued by us
        result = jwt.verify(token, process.env.JWT_SECRET, options);

        // Let's pass back the decoded token to the request object
        req.decoded = result;
        // We call next to pass execution to the subsequent middleware
        next();
      } catch (err) {
        // Throw an error just in case anything goes wrong with verification
        throw new Error(err);
      }
    } else {
      result = { 
        error: `Authentication error. Token required.`,
        status: 401
      };
      res.status(401).send(result);
    }
  }
};

Let’s add our function to our router so that it’s called before our getAll controller. If validateToken throws an error, controller.getAll won’t be called. Also, if it sends a response with an error, since we haven’t called next in our else block, getAll won’t be called either.

routes/users.js

const controller = require('../controllers/users');
const validateToken = require('../utils').validateToken;

module.exports = (router) => {
  router.route('/users')
    .post(controller.add)
    .get(validateToken, controller.getAll); // This route is now protected

  router.route('/login')
    .post(controller.login);
};

If we leave it as is, all users with a token will be able to access a list of our users but, we only want admins to do this. Let’s make a few final tweaks to our controller to achieve this.

controllers/users.js

getAll: (req, res) => {
    mongoose.connect(connUri, { useNewUrlParser: true }, (err) => {
      let result = {};
      let status = 200;
      if (!err) {
        const payload = req.decoded;
        // TODO: Log the payload here to verify that it's the same payload
        //  we used when we created the token
        // console.log('PAYLOAD', payload);
        if (payload && payload.user === 'admin') {
          User.find({}, (err, users) => {
            if (!err) {
              result.status = status;
              result.error = err;
              result.result = users;
            } else {
              status = 500;
              result.status = status;
              result.error = err;
            }
            res.status(status).send(result);
          });
        } else {
          status = 401;
          result.status = status;
          result.error = `Authentication error`;
          res.status(status).send(result);
        }
      } else {
        status = 500;
        result.status = status;
        result.error = err;
        res.status(status).send(result);
      }
    });
  }

As you can see below, if we don’t pass a token in our authorization headers, we’re refused access.

Here’s what happens when we pass an invalid token.

There it is, our middlware is working as intended. Congratulations!

When we pass the token we got from logging in as our admin, we’re allowed to retrieve our users list.

Conclusion

We’ve covered a lot in this article. As a recap, we’ve learned:

  1. Setting up our development environment and initializing our express server.
  2. Creating our first basic route and controller.
  3. Fleshing out our routes and controllers to add users and login users.
  4. Creating a route and controller that will handle getting all users.

*Originally published by Elizabeth Mabishi at *https://scotch.io

Learn More

10 Node Frameworks to Use in 2019

JavaScript ES6 Classes

The JavaScript Developer’s Guide To Node.JS

Machine Learning In Node.js With TensorFlow.js

Full Stack Developers: Everything You Need to Know

ES5 to ESNext — here’s every feature added to JavaScript since 2015

How to Perform Web-Scraping using Node.js

12 Concepts That Will Level Up Your JavaScript Skills

Vuejs 2 Authentication Tutorial

The Full JavaScript & ES6 Tutorial - (including ES7 & React)

The Complete Node.js Developer Course (3rd Edition)

#node-js #javascript #json #web-development

What is GEEK

Buddha Community

Authenticate a Node ES6 API with JSON Web Tokens

Top 10 API Security Threats Every API Team Should Know

As more and more data is exposed via APIs either as API-first companies or for the explosion of single page apps/JAMStack, API security can no longer be an afterthought. The hard part about APIs is that it provides direct access to large amounts of data while bypassing browser precautions. Instead of worrying about SQL injection and XSS issues, you should be concerned about the bad actor who was able to paginate through all your customer records and their data.

Typical prevention mechanisms like Captchas and browser fingerprinting won’t work since APIs by design need to handle a very large number of API accesses even by a single customer. So where do you start? The first thing is to put yourself in the shoes of a hacker and then instrument your APIs to detect and block common attacks along with unknown unknowns for zero-day exploits. Some of these are on the OWASP Security API list, but not all.

Insecure pagination and resource limits

Most APIs provide access to resources that are lists of entities such as /users or /widgets. A client such as a browser would typically filter and paginate through this list to limit the number items returned to a client like so:

First Call: GET /items?skip=0&take=10 
Second Call: GET /items?skip=10&take=10

However, if that entity has any PII or other information, then a hacker could scrape that endpoint to get a dump of all entities in your database. This could be most dangerous if those entities accidently exposed PII or other sensitive information, but could also be dangerous in providing competitors or others with adoption and usage stats for your business or provide scammers with a way to get large email lists. See how Venmo data was scraped

A naive protection mechanism would be to check the take count and throw an error if greater than 100 or 1000. The problem with this is two-fold:

  1. For data APIs, legitimate customers may need to fetch and sync a large number of records such as via cron jobs. Artificially small pagination limits can force your API to be very chatty decreasing overall throughput. Max limits are to ensure memory and scalability requirements are met (and prevent certain DDoS attacks), not to guarantee security.
  2. This offers zero protection to a hacker that writes a simple script that sleeps a random delay between repeated accesses.
skip = 0
while True:    response = requests.post('https://api.acmeinc.com/widgets?take=10&skip=' + skip),                      headers={'Authorization': 'Bearer' + ' ' + sys.argv[1]})    print("Fetched 10 items")    sleep(randint(100,1000))    skip += 10

How to secure against pagination attacks

To secure against pagination attacks, you should track how many items of a single resource are accessed within a certain time period for each user or API key rather than just at the request level. By tracking API resource access at the user level, you can block a user or API key once they hit a threshold such as “touched 1,000,000 items in a one hour period”. This is dependent on your API use case and can even be dependent on their subscription with you. Like a Captcha, this can slow down the speed that a hacker can exploit your API, like a Captcha if they have to create a new user account manually to create a new API key.

Insecure API key generation

Most APIs are protected by some sort of API key or JWT (JSON Web Token). This provides a natural way to track and protect your API as API security tools can detect abnormal API behavior and block access to an API key automatically. However, hackers will want to outsmart these mechanisms by generating and using a large pool of API keys from a large number of users just like a web hacker would use a large pool of IP addresses to circumvent DDoS protection.

How to secure against API key pools

The easiest way to secure against these types of attacks is by requiring a human to sign up for your service and generate API keys. Bot traffic can be prevented with things like Captcha and 2-Factor Authentication. Unless there is a legitimate business case, new users who sign up for your service should not have the ability to generate API keys programmatically. Instead, only trusted customers should have the ability to generate API keys programmatically. Go one step further and ensure any anomaly detection for abnormal behavior is done at the user and account level, not just for each API key.

Accidental key exposure

APIs are used in a way that increases the probability credentials are leaked:

  1. APIs are expected to be accessed over indefinite time periods, which increases the probability that a hacker obtains a valid API key that’s not expired. You save that API key in a server environment variable and forget about it. This is a drastic contrast to a user logging into an interactive website where the session expires after a short duration.
  2. The consumer of an API has direct access to the credentials such as when debugging via Postman or CURL. It only takes a single developer to accidently copy/pastes the CURL command containing the API key into a public forum like in GitHub Issues or Stack Overflow.
  3. API keys are usually bearer tokens without requiring any other identifying information. APIs cannot leverage things like one-time use tokens or 2-factor authentication.

If a key is exposed due to user error, one may think you as the API provider has any blame. However, security is all about reducing surface area and risk. Treat your customer data as if it’s your own and help them by adding guards that prevent accidental key exposure.

How to prevent accidental key exposure

The easiest way to prevent key exposure is by leveraging two tokens rather than one. A refresh token is stored as an environment variable and can only be used to generate short lived access tokens. Unlike the refresh token, these short lived tokens can access the resources, but are time limited such as in hours or days.

The customer will store the refresh token with other API keys. Then your SDK will generate access tokens on SDK init or when the last access token expires. If a CURL command gets pasted into a GitHub issue, then a hacker would need to use it within hours reducing the attack vector (unless it was the actual refresh token which is low probability)

Exposure to DDoS attacks

APIs open up entirely new business models where customers can access your API platform programmatically. However, this can make DDoS protection tricky. Most DDoS protection is designed to absorb and reject a large number of requests from bad actors during DDoS attacks but still need to let the good ones through. This requires fingerprinting the HTTP requests to check against what looks like bot traffic. This is much harder for API products as all traffic looks like bot traffic and is not coming from a browser where things like cookies are present.

Stopping DDoS attacks

The magical part about APIs is almost every access requires an API Key. If a request doesn’t have an API key, you can automatically reject it which is lightweight on your servers (Ensure authentication is short circuited very early before later middleware like request JSON parsing). So then how do you handle authenticated requests? The easiest is to leverage rate limit counters for each API key such as to handle X requests per minute and reject those above the threshold with a 429 HTTP response. There are a variety of algorithms to do this such as leaky bucket and fixed window counters.

Incorrect server security

APIs are no different than web servers when it comes to good server hygiene. Data can be leaked due to misconfigured SSL certificate or allowing non-HTTPS traffic. For modern applications, there is very little reason to accept non-HTTPS requests, but a customer could mistakenly issue a non HTTP request from their application or CURL exposing the API key. APIs do not have the protection of a browser so things like HSTS or redirect to HTTPS offer no protection.

How to ensure proper SSL

Test your SSL implementation over at Qualys SSL Test or similar tool. You should also block all non-HTTP requests which can be done within your load balancer. You should also remove any HTTP headers scrub any error messages that leak implementation details. If your API is used only by your own apps or can only be accessed server-side, then review Authoritative guide to Cross-Origin Resource Sharing for REST APIs

Incorrect caching headers

APIs provide access to dynamic data that’s scoped to each API key. Any caching implementation should have the ability to scope to an API key to prevent cross-pollution. Even if you don’t cache anything in your infrastructure, you could expose your customers to security holes. If a customer with a proxy server was using multiple API keys such as one for development and one for production, then they could see cross-pollinated data.

#api management #api security #api best practices #api providers #security analytics #api management policies #api access tokens #api access #api security risks #api access keys

I am Developer

1602036957

Laravel 8 REST API Authentication with Passport Example Tutorial

Laravel 8 rest api authentication with passport tutorial, you will learn step by step how to create rest API with laravel 8 passport authentication. And as well as how to install and cofigure passport auth in laravel 8 app.

Laravel 8 API Authentication with Passport Tutorial

Step 1: Download Laravel 8 App
Step 2: Database Configuration
Step 3: Install Passport Auth
Step 4: Passport Configuration
Step 5: Run Migration
Step 6: Create APIs Route
Step 7: Create Passport Auth Controller
Step 8: Now Test Laravel REST API in Postman

https://www.tutsmake.com/laravel-8-rest-api-authentication-with-passport/

#laravel api authentication with passport #laravel 8 api authentication #laravel 8 api authentication token tutorial #laravel 8 api authentication using passport #laravel 8 api authentication session

Vicenta  Hauck

Vicenta Hauck

1627702260

How to Authenticate a Node ES6 API with JSON Web Tokens

We'll be implementing token based authentication in our own node.js A.P.I. using JSON web tokens. We create 3 endpoints: register (create a new user), login (login user), and get all users (this route is restricted, only verifying users can access, we need a JWT to able to get access to this route).

  • Information:
    ✔  Backend: NodeJS and MySQL (using ORM with Sequelize package)
    ✔ Testing APIs with Postman

✨Get full source code at my Github: https://github.com/haryphamdev/nodejs-jwt

#node #api #json #github 

Autumn  Blick

Autumn Blick

1601381326

Public ASX100 APIs: The Essential List

We’ve conducted some initial research into the public APIs of the ASX100 because we regularly have conversations about what others are doing with their APIs and what best practices look like. Being able to point to good local examples and explain what is happening in Australia is a key part of this conversation.

Method

The method used for this initial research was to obtain a list of the ASX100 (as of 18 September 2020). Then work through each company looking at the following:

  1. Whether the company had a public API: this was found by googling “[company name] API” and “[company name] API developer” and “[company name] developer portal”. Sometimes the company’s website was navigated or searched.
  2. Some data points about the API were noted, such as the URL of the portal/documentation and the method they used to publish the API (portal, documentation, web page).
  3. Observations were recorded that piqued the interest of the researchers (you will find these below).
  4. Other notes were made to support future research.
  5. You will find a summary of the data in the infographic below.

Data

With regards to how the APIs are shared:

#api #api-development #api-analytics #apis #api-integration #api-testing #api-security #api-gateway

Einar  Hintz

Einar Hintz

1599364620

API Integration Practices and Patterns

We all hear it so often that we almost stop hearing it: “Integration is critical to meeting users’ needs.”

Integration work consumes 50%-80% of the time and budget of digital transformation projects, or building a digital platform, while innovation gets only the leftovers, according to SAP and Salesforce. And as everyone from legacy enterprises to SaaS startups launches new digital products, they all hit a point at which the product cannot unlock more value for users or continue to grow without making integration a feature.

If I were to sum up the one question behind all of the other questions that I hear from customers, enterprises, partners, and developers, it would be something like: “Is integration a differentiator that we should own? Or an undifferentiated but necessary feature that supports what we’re trying to accomplish?”

This Refcard won’t try to answer that question for you. Rather, no matter what type of development work you do, API integration is a fact of life today, like gravity. Why? Today, experience is paramount. The average enterprise uses more than 1,500 cloud applications (with the number growing by 20% each year). Every app needs to integrate with other systems in a fluid and ever-changing application ecosystem. So instead, I’ll share some of the common practices you’re likely to contend with as well as some patterns to consider.


This is a preview of the API Integrations Practices and Patterns Refcard. To read the entire Refcard, please download the PDF from the link above.

#apis #api integration #integration patterns #api cloud #api patterns #api authentication #api errors #apis and integrations