Archie  Clayton

Archie Clayton

1559628013

Sessionless Authentication using JWTs

Learn the intricate theory and practice of sessionless authentication using JWTs (with Node + Express + Passport JS) along with best practices

Authentication using stateful user sessions and session_ids stored in the cookie has been a strategy that has worked for decades. But with the rise of service oriented architectures and web services, there has been a push to design applications with the principle of statelessness in mind.

JWTs provide a *stateless *solution to **authentication **by removing the need to track session data on the server. Instead, JWTs allow us to safely and securely store our session data directly on the client in the form of a JWT.

A JWT is essentially a session data payload packaged in JSON and signed by the server

**JWTs **get a lot of criticism and skepticism, but the fact of the matter is that both session and JWT authentication have seen plenty of production usage and both implementations are secure and robust when it comes to handling user authentication. If statelessness is a practice you value in your system architecture, then JWTs are right for you. In this article, we will go over what JWTs are, the trade offs you make in choosing to use JWTs, and how you can implement them securely in your architecture.

How Authentication works

Before we begin, we need to agree what an authentication pipeline looks like:

  1. User POSTs to our server authentication details (over HTTPS):⠀⠀⠀⠀⠀⠀⠀ { username, password }
  2. The server determines whether the user is who she claims to be
  3. If the user’s *authentication *attempt succeeds, then our server sends some form of data (a token or a session id conventionally) that can be appended to every subsequent request which identifies the user as *authenticated *or not.

With sessionless auth, the data payload the client receives is our JWT, which should contain an encoded user identifier in JSON format signed by our back-end server. We put the *JWT *into our cookie so that we don’t have to store it in local-storage and risk XSS attacks. This is what an authentication process for a user named TheLegend27 might look like using JWTs:

A cookie is a special header that will be sent along with every subsequent request. It also conveniently persists across user sessions. This means that once TheLegend27 has logged in, her *JWT *will be sent along with every subsequent request she makes. All we have to do to verify her identity is to check the request cookie and verify the JWT.

Some important things to note:

  • We don’t keep track of user sessions on the server! 🙌 This is the big difference between *JWT *auth and *auth *using sessions. We have one less data source to worry about in our architecture with sessionless auth.
  • Our auth pipeline is super simple! If you’re just trying to implement authentication into your web app as intuitively and quickly as possible, then *JWTs *are the way to go.

So that’s the theory behind sessionless authentication using JWTs. Now if you have familiarity with *authentication *using sessions, this pipeline might look somewhat familiar. A JWT looks very similar to a HS256 encrypted session_id stored in the cookie. In fact, *JWTs *by default are signed using HS256! The difference between the two is that a JWT encodes all session data in its payload, while a session_id references a session from a sessions table.

JWTs remove the need keep track of sessions on the back-end. Instead, session data is encoded in the JWT payload. The trade off being made here is that the size of a JWT scales proportionally to the size of its payload. Luckily, a payload that takes the shape of {user_id, expiration_date } is plenty enough for most cases.

So that’s the theory. Lets get on to the practice!

Before discussing implementation, let’s discuss best practices in order to protect ourselves against the most common kinds of attacks / vulnerabilities when it comes to authentication:

  • XSS and SQL / noSQL injection attacks
  • Brute-forcing of user credentials attacks
  • An attacker getting a hold of a user’s JWT / cookie
  • An attacker getting a copy of or read credentials to our database

JWTs and best practices can protect us against all of these attacks. Let’s see how:

XSS attacks

This kind of attack is the simplest attack to protect ourselves against. A naive way to protect ourselves against XSS and code injection is to sanitize user input by doing the something like _.escape(<em>userInput</em>). But the issue with this solution is that when it comes to private data, it’s naive to blindly trust libraries to properly sanitize user input against sql xss attacks. Input sanitization is a great first layer of defense, but isn’t enough by itself.

Some more sturdy ways we can protect our user’s sensitive data is to use an ORM / ODM, which enforces parameterized queries. Or we could use Stored Procedures if we’re using SQL, which defines the query procedure at the database level as opposed to the code level.

If XSS and query sanitization best practices interest you, I highly recommend this resource by the Open Web Application Security Project Foundation on best practices to preventing XSS injection attacks.

Bruteforce User credential attacks

There are two ways an attacker will brute force user credentials:

A) They’ll attack a single user and try permutations of passwords until they hit a match.

B) They’ll attack a multitude of users and use a list of the most commonly used passwords to shallowly brute force until they find a hit. Here’s an excellent example of this: https://hackernoon.com/picking-the-low-hanging-passwords-b64684fe2c7

We can’t protect our users much from attack B. If a user sets their password to p@ssw0rd, then there’s not much we can do besides enforce stricter password policies in the future.

It turns out we can protect ourselves very well from attack A. The key is in making login requests take a non-trivial amount of time to process. An attacker can’t brute-force a user’s credentials if it takes 10¹¹ permutations to crack a 8 character password when each permutation takes 500ms to compute. We can make authentication take a non-trivial amount of time using a library called Bcrypt, which we’ll cover later.

Compromised JWT

This is the worst possible attack we can come across because it’s the hardest to resolve. Luckily, JWTs should rarely become compromised as we’re storing the JWT as a cookie and using HTTPS for all web transactions. Since we’re never storing the JWT in LocalStorage and only ever in the cookie, malicious attackers will not be able to steal our user’s JWT using XSS.

If an attacker somehow manages to steal a user’s JWT, then there’s unfortunately not much that can really be done. To minimize damages, you should design your application to require reauthentication before performing any high profile transaction such as a purchase or the changing of a password. And your JWTs should also have an expiration date. That way a compromised JWT will only work for so long.

This is what appears when you open the developer console on Facebook.com. This is a great way of preventing self-xss

Compromised Database

It turns out there are things we can do to protect user data and keep it obfuscated even if a hacker gets a hold of our database read credentials.

If we have a password, we don’t want to store it as plain-text in our database. Instead, we can salt and hash the password and store the salt and hash instead of our plain-text password.

Imagine we have a password p@ssw0rd. A salt is a random string of characters that we append to that password 'p@ssw0rd' + 'asdf253$n5', which we then pass through a hashing algorithm: SHA256('p@ssw0rd' + 'asdf253$n5'). We then store the salt and the hashed value in our user table.

An attacker can’t compute a user’s password with just a salt and hash.

This protects our user’s passwords pretty well if our database becomes compromised. You’ll still have to take action by for example requesting all users reset their passwords, but this will buy you plenty of time to do so.

It turns out there’s a standardized way of salting and hashing your password in a way that doesn’t require us to have a salt and hash field in our user table. The solution is called Bcrypt.

Bcrypt

Bcrypt is a password hashing algorithm that’s been around since 1999. It standardizes the salting and hashing of passwords. It also protects passwords from being brute-forced by making the process of authentication computationally intensive and “slow as hell.” We’ll be using this in our authentication implementation.

This is what a password passed through Bcrypt looks like. It contains the hashing algorithm version, hash cost, salt value and hashed password value.

The higher the hash cost, the more computational power it takes to authenticate

Now that we have all this in mind, let’s get to implementing authentication.

I’m going to be using MongoDB but feel free to use any database of choice. Nothing crazy here. This is just an ordinary User Schema:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({
  username: {
    type: String,
    index: true,
    unique: true,
    dropDups: true,
    required: true,
  },
  passwordHash: { //salted and hashed using bcrypt
    type: String,
    required: true,
  },
});

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

Next, we’re going to register two Passport strategies. We’re going to set up a Local Strategy and a JWT Strategy. In the future, when we call passport.authenticate(<em>'local'</em>) or passport.authenticate(<em>'jwt'</em>), it’s going to invoke these respective middlewares.

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const passportJWT = require('passport-jwt');
const JWTStrategy = passportJWT.Strategy;
const bcrypt = require('bcrypt');

const { secret } = require('./keys');

const UserModel = require('./models/user');

passport.use(new LocalStrategy({
  usernameField: username,
  passwordField: password,
}, async (username, password, done) => {
  try {
    const userDocument = await UserModel.findOne({username: username}).exec();
    const passwordsMatch = await bcrypt.compare(password, userDocument.passwordHash);

    if (passwordsMatch) {
      return done(null, userDocument);
    } else {
      return done('Incorrect Username / Password');
    }
  } catch (error) {
    done(error);
  }
}));

passport.use(new JWTStrategy({
    jwtFromRequest: req => req.cookies.jwt,
    secretOrKey: secret,
  },
  (jwtPayload, done) => {
    if (Date.now() > jwtPayload.expires) {
      return done('jwt expired');
    }

    return done(null, jwtPayload);
  }
));

The Local strategy extracts the username and password from req.body and verifies the user by verifying it against the User table.

The JWT strategy extracts the JWT from the cookie, and uses the application’s secret to verify its signature:

The signature is dependent on the payload. If a user tampers with and changes the payload, then the signature changes as well

Now, last but not least, we define our /login and /register routes:

const express = require('express');
const passport = require('passport');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const keys = require('../keys');
const UserModel = require('../models/user');

const router = express.Router();

router.post('/register', async (req, res) => {
  const { username, password } = req.body;

  // authentication will take approximately 13 seconds
  // https://pthree.org/wp-content/uploads/2016/06/bcrypt.png
  const hashCost = 10;

  try {
    const passwordHash = await bcrypt.hash(password, hashCost);
    const userDocument = new UserModel({ username, passwordHash });
    await userDocument.save();
    
    res.status(200).send({ username });
    
  } catch (error) {
    res.status(400).send({
      error: 'req body should take the form { username, password }',
    });
  }
});

router.post('/login', (req, res) => {
  passport.authenticate(
    'local',
    { session: false },
    (error, user) => {

      if (error || !user) {
        res.status(400).json({ error });
      }

      /** This is what ends up in our JWT */
      const payload = {
        username: user.username,
        expires: Date.now() + parseInt(process.env.JWT_EXPIRATION_MS),
      };

      /** assigns payload to req.user */
      req.login(payload, {session: false}, (error) => {
        if (error) {
          res.status(400).send({ error });
        }

        /** generate a signed json web token and return it in the response */
        const token = jwt.sign(JSON.stringify(payload), keys.secret);

        /** assign our jwt to the cookie */
        res.cookie('jwt', jwt, { httpOnly: true, secure: true });
        res.status(200).send({ username });
      });
    },
  )(req, res);
});

module.exports = router;

/register is pretty straight forward. We’re creating a new User and saving it to our Users table and responding with status 200 if we succeed.

/login is a bit more complicated. A break down of what’s going on: We’re authenticating with the local strategy. If authentication succeeds, we compose a payload for our JWT, and call req.login, which assigns the payload to req.user. We then compose our JWT by callingjwt.sign, and then we set our JWT to our cookie.

Now, if we need to create a route that requires authentication, we can use our JWT middleware to check if the user is authenticated!

router.get('/protected',
  passport.authenticate('jwt', {session: false}),
  (req, res) => {
    const { user } = req;

    res.status(200).send({ user });
  });

Conclusion

That’s it! There’s a whole rabbit-hole awaiting those who are interested in security and authentication. I’ve personally been stuck in this rabbit hole for far longer than I care to admit.

This article is the culmination of my research into best practices with JWTs and it should be enough to get your feet wet with sessionless auth. JWTs are an elegant solution to authentication and I hope this article has shed some light on how they work and how you can implement them yourself securely.

#javascript #node-js #express #security #web-development

What is GEEK

Buddha Community

Sessionless Authentication using JWTs

How To Set Up Two-Factor Authentication in cPanel

What is 2FA
Two-Factor Authentication (or 2FA as it often referred to) is an extra layer of security that is used to provide users an additional level of protection when securing access to an account.
Employing a 2FA mechanism is a vast improvement in security over the Singe-Factor Authentication method of simply employing a username and password. Using this method, accounts that have 2FA enabled, require the user to enter a one-time passcode that is generated by an external application. The 2FA passcode (usually a six-digit number) is required to be input into the passcode field before access is granted. The 2FA input is usually required directly after the username and password are entered by the client.

#tutorials #2fa #access #account security #authentication #authentication method #authentication token #cli #command line #cpanel #feature manager #google authenticator #one time password #otp #otp authentication #passcode #password #passwords #qr code #security #security code #security policy #security practices #single factor authentication #time-based one-time password #totp #two factor authentication #whm

Why Use WordPress? What Can You Do With WordPress?

Can you use WordPress for anything other than blogging? To your surprise, yes. WordPress is more than just a blogging tool, and it has helped thousands of websites and web applications to thrive. The use of WordPress powers around 40% of online projects, and today in our blog, we would visit some amazing uses of WordPress other than blogging.
What Is The Use Of WordPress?

WordPress is the most popular website platform in the world. It is the first choice of businesses that want to set a feature-rich and dynamic Content Management System. So, if you ask what WordPress is used for, the answer is – everything. It is a super-flexible, feature-rich and secure platform that offers everything to build unique websites and applications. Let’s start knowing them:

1. Multiple Websites Under A Single Installation
WordPress Multisite allows you to develop multiple sites from a single WordPress installation. You can download WordPress and start building websites you want to launch under a single server. Literally speaking, you can handle hundreds of sites from one single dashboard, which now needs applause.
It is a highly efficient platform that allows you to easily run several websites under the same login credentials. One of the best things about WordPress is the themes it has to offer. You can simply download them and plugin for various sites and save space on sites without losing their speed.

2. WordPress Social Network
WordPress can be used for high-end projects such as Social Media Network. If you don’t have the money and patience to hire a coder and invest months in building a feature-rich social media site, go for WordPress. It is one of the most amazing uses of WordPress. Its stunning CMS is unbeatable. And you can build sites as good as Facebook or Reddit etc. It can just make the process a lot easier.
To set up a social media network, you would have to download a WordPress Plugin called BuddyPress. It would allow you to connect a community page with ease and would provide all the necessary features of a community or social media. It has direct messaging, activity stream, user groups, extended profiles, and so much more. You just have to download and configure it.
If BuddyPress doesn’t meet all your needs, don’t give up on your dreams. You can try out WP Symposium or PeepSo. There are also several themes you can use to build a social network.

3. Create A Forum For Your Brand’s Community
Communities are very important for your business. They help you stay in constant connection with your users and consumers. And allow you to turn them into a loyal customer base. Meanwhile, there are many good technologies that can be used for building a community page – the good old WordPress is still the best.
It is the best community development technology. If you want to build your online community, you need to consider all the amazing features you get with WordPress. Plugins such as BB Press is an open-source, template-driven PHP/ MySQL forum software. It is very simple and doesn’t hamper the experience of the website.
Other tools such as wpFoRo and Asgaros Forum are equally good for creating a community blog. They are lightweight tools that are easy to manage and integrate with your WordPress site easily. However, there is only one tiny problem; you need to have some technical knowledge to build a WordPress Community blog page.

4. Shortcodes
Since we gave you a problem in the previous section, we would also give you a perfect solution for it. You might not know to code, but you have shortcodes. Shortcodes help you execute functions without having to code. It is an easy way to build an amazing website, add new features, customize plugins easily. They are short lines of code, and rather than memorizing multiple lines; you can have zero technical knowledge and start building a feature-rich website or application.
There are also plugins like Shortcoder, Shortcodes Ultimate, and the Basics available on WordPress that can be used, and you would not even have to remember the shortcodes.

5. Build Online Stores
If you still think about why to use WordPress, use it to build an online store. You can start selling your goods online and start selling. It is an affordable technology that helps you build a feature-rich eCommerce store with WordPress.
WooCommerce is an extension of WordPress and is one of the most used eCommerce solutions. WooCommerce holds a 28% share of the global market and is one of the best ways to set up an online store. It allows you to build user-friendly and professional online stores and has thousands of free and paid extensions. Moreover as an open-source platform, and you don’t have to pay for the license.
Apart from WooCommerce, there are Easy Digital Downloads, iThemes Exchange, Shopify eCommerce plugin, and so much more available.

6. Security Features
WordPress takes security very seriously. It offers tons of external solutions that help you in safeguarding your WordPress site. While there is no way to ensure 100% security, it provides regular updates with security patches and provides several plugins to help with backups, two-factor authorization, and more.
By choosing hosting providers like WP Engine, you can improve the security of the website. It helps in threat detection, manage patching and updates, and internal security audits for the customers, and so much more.

Read More

#use of wordpress #use wordpress for business website #use wordpress for website #what is use of wordpress #why use wordpress #why use wordpress to build a website

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

Alice Cook

Alice Cook

1615441648

Fix: Gmail Authentication Problems | Gmail 2-step Verification Bypass (2020-21)

An Gmail authentication error occurs when an account’s owner is unable to verify themselves; Gmail perceives it to be a threat to the account and its privacy, so it shows an authentication error. This can occur due to multiple reasons; entering the wrong password, using the wrong server port, and disabled IMAP on Gmail. You will find solutions to fix Gmail authentication problems in this Video. Additionally, you will find ways for Gmail 2-step verification bypass.
Visit: https://contactforhelp.com/gmail/

#gmail authentication error #gmail two factor authentication #gmail 2 step authentication #gmail authentication failed #gmail authentication problems #gmail 2 step verification bypass

Chaz  Homenick

Chaz Homenick

1599056059

Google's Authenticator App Explained and Reviewed

Such a cool-sounding term, I had to find out its meaning and purpose. So here is the story.

Let’s take the story step-wise. You should have heard by now of 2-FA, two-factor authentication. The base idea is pretty simple. Apart from just the password, many of the websites might be sending you an OTP on the phone to grant access. That summarises the two factors. Your password is factor one, and possession of your phone number is factor 2. But just for curious people, I will share some knowledge.

Multi-Factor Authentication

In information security, we have three main pillars to verify someone’s identity.

  • **Knowledge: **Something only the user knows
  • **Possession: **Something only the user has
  • Inherence: Something only the user is

Withdrawing money from ATM checks _possession _of ATM card and knowledge of the PIN. Encashing a cheque checks possession of the cheque book and inherence to the user’s signature. Attendance in my college lectures needs inherence to fingerprint and possession of the ID card. Writing proxy attendance in attendance sheet requires knowledge of friend’s roll number and _inherence _of the fake signature of your friend. You get the idea where it’s going.

Two-Factor authentication, as most of the examples above, is about combining the methods from 2 separate domains. It is different from Two-Step authentication, which can be just a password and a pin, both from the _knowledge _domain.

Where does Google Authenticator come in?

Many secure websites recommend, even enforce you, to use such two factors. More than often, the possession part is your phone number.

But waiting for OTP can be troublesome, especially in a place with poor networking. Many people may be stuck in places that do have good WiFi, internet connectivity but horrible cellular coverage. Like any place in the new CSE building of my college or even Chhatrapati Shivaji Maharaj International Airport in rush hours.

Why so many worries, right? If we just wanted to prove the possession of something, can’t we show the possession of our phone? Something that we always have. And more than often is the device we are using to log in to the website. This is the idea behind Google Authenticator.

How does it work?

At the time of first account creation, if you choose the authenticator app option in the available list, they will provide you with a QR code, which is the main secret that will remain shared between your phone and the website. You should print this QR code and keep it hidden in your cupboard or somewhere you can be safe about. Why? We will come to that later.

Ease of use

This secret that is shared through QR is more than often 16+ length of a random string. So are you supposed to type in every time? That will not only make it tough but also make the string knowledge than possession.

Instead, what the app does for you is taking this secret key and the current time as inputs, it generates a new OTP for you which is a 6–8 digit number that you can type in. This OTP is regenerated in 30 seconds and older OTP expires.

A Cyber hacker has to guess the OTP in a small time window. Anything later than that and the OTP will expire. This will not only prevent the entry but also warn the user through email about his password being compromised.

#two-factor-authentication #multifactor-authentication #google-authenticator #android #password-manager #authentication #technology #hackernoon-top-story