Adam Rose

Adam Rose

1560503417

The Complete Guide to JSON Web Tokens

In this article, we will take a look at what JSON Web Token is all about and hands-on guide to JSON Web Token Authentications

JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred between two parties.

We will start with a basic explanation of JWT, then look at its structure, and finally create a simple server that will take some data and insert it into a JWT.

What is a JSON Web Token and why do we need it?

A **JSON Web Token (JWT) **is a safe, compact, and self-contained way of transmitting information between multiple parties in the form of a JSON object.

Say you want to log in to an app, like say Tinder. Tinder allows users to log in using their Facebook profile. So when the user selects the option to log in using Facebook, the app contacts Facebook’s Authentication server with the user’s credentials (username and password).

Once the Authentication server verifies the user’s credentials, it will create a **JWT **and sends it to the user. The app now gets this JWT and allows the user access to its data.

JWT’s Structure

A JSON Web Token consists of three parts that are separated by a “.”. They are:

  • Header
  • Payload
  • Signature

The header typically consists of two parts: the token’s type, and the hashing algorithm that is being used.

{
  "alg": "HS256",
  "typ": "JWT"
}

The payload is where the actual information that we want to send is stored. Here is an example of a simple payload. Know that payloads can be way more complicated than this to ensure better security.

{
  "sub": "65165751325",
  "name": "Rajat S",
  "admin": true
}

The signature is used to verify that the message was not altered before reaching its destination. This is usually done by using private keys.

These three parts are usually encoded into three Base64-URI strings that are separated by a . in between them.

To easily decode, verify, generate, or just play around with JWTs, check out the JWT.IO Debugger by Auth0.

Now that we have a basic understanding of what a JSON is, lets take a look at how to build a simple authentication server that will issue JWT, which we will then use to access an API.

Getting Started

To get started, lets build a simple web server. First, install the express library onto your system using NPM. Simply open a command terminal and run the command:

$ npm install express

Next, create a new folder named jwt-auth. You can name it something else if you want.

$ mkdir jwt-auth
$ cd jwt-auth

Inside this folder create a new file called index.js. This where we will write our code to set up a web server that will have a single route that displays the current date and time and a handler for 404 pages.

Open a code editor (I ❤ VS Code) write the following code inside it:

const express = require("express");
const app = express();
const PORT = 8888;
app.get('/time', (req, res) => {
  const time = (new Date()).toLocaleTimeString();
  res.status(200).send(`The Time is ${time}`);
});

Here, we are first importing the express library that we had just installed. Then I am creating a new const called app that will use the express library. I am also creating another const called PORT which will contain the port number on which our server will run. I have selected 8888 as the port number. You can use any other port number if you want as well.

Next, I have created a new route called time. This route takes a callback with response and request as parameters. In short, this route will display the current local time to the user.

Let’s also add a route for the case when tell the server to takes us anywhere but to time. This is called a **catchall route. **I want the server to return a 404 error on this route. To implement this, write the following code into our index.js file:

app.get("*", (req, res) => {
  res.sendStatus(404);
});

One last thing left to do. We have not told our server on which port to listen. We have initialized the PORT number as 8888. But we have yet to actually use this const in our code. To do this, use the app.listen method as shown below:

app.listen(PORT, () => {     
  console.log(`Server is running on port ${PORT}.`); 
});

With that done, we can start the server by typing node . in our command terminal. Then, go to localhost:8888 and you will find that it displays a Not Found message. Add /time to the URL and it will not display the local time as shown below:

In short, we have built an express server that will show us the local time at /time and a 404 error on any other route.

Implementing a Login Route

Since this article is about JWT Authentication, let’s implement a route called login. Unlike the routes in the previous sections, which used get and listen, this route will be created using post.

app.post("/login", (req, res) => {
  const user = req.body.username;
  res.status(200).send(`User's name is ${user}`);
})

But currently our server cannot read the body of the requests. To solve this, we will install a new middleware library called body-parser.

$ npm install body-parser

Then just like we did with the express library, import it into the index.js file using the require syntax.

const bodyParser = require("body-parser");

We can now tell express to use body-parser to handle all the JSON responses as shown below:

app.use(bodyParser.json());

Now start the server by running the node . command.

In order, to test this new route, we will need to use POSTMAN. Install this into your system, if you don’t already have it.

Inside POSTMAN, create a post request to the login route as shown below:

Inside the body, create a JSON Object as shown below:

Clicking on send should get you the following response:

Issuing JWTs

Now that we have built a simple server that can handle GET, and POST requests, let’s build a simple JWT issuer.

Lets start by creating a new array called users that will contain a couple of users along with their passwords as shown below:

const users = [
  {id: 1, username: "clarkKent", password: "superman"},
  {id: 2, username: "bruceWayne", password: "batman"}
];

Lets rewrite the /login route. Here, we will first check if the submitted request contains both a username and password. If that is not the case, then the server should respond with a 400 status.

app.post("/login", (req, res) => {
  if (!req.body.username || !req.body.password) {
    res.status(400).send("Error. Please enter the correct username and password");
    return;
  }

Next, if the request valid, we will need to check if the user in the request is present in our users array. In the same /login route below the if statement, write:

const user = users.find((u) => {
  return u.username === req.body.username && u.password === req.body.password;
});

But if the user in the request is not present in the users array, we need to respond with a status code of 401. Again in the same /login route, write:

Before going forward, let’s install another library called the jsonwebtoken.

$ npm install jsonwebtoken

At the top of the index.js file, write the require statement for the jsonwebtoken library as shown below:

const jwt = require("jsonwebtoken");

We will use this library to create a JSON Web Token for every valid user. To do this, we will create a new const called token using the sign method from the jsonwebtoken library. Note that we are still writing the code inside the /login route.

const token = jwt.sign({
  sub: user.id,
  username: user.username
}, "mykey", {expiresIn: "3 hours"});
res.status(200).send({access_token: token})

Now go to POSTMAN, and send a post request with the following JSON object in its body.

{
  "username": "clarkKent",
  "password": "superman",
}

The result will be a JSON Web Token as shown below:

If you copy the value of access_token into the JWT.IO Debugger, you will see that it is the same username and password, but with a few extra things.

Side note — CORS

In some cases where the API that your app tries to access is running on a different server than that of your app’s, will return some kind of **Failed To Load **error.

To prevent this from happening, we can install another library called cors

$ npm install cors

Then at the top of the index.js file, write the require statement for this library as shown below:

const cors = require("cors");

Then similar to what we did with the body-parser library, we will tell the express to use cors as shown below:

app.use(cors());

Provide User Access To An API using JWT

Here, we will create a new API with two routes. The first route will be public, while the second one will require the user to be authenticated using **JWT **into order to access it.

Let’s create a new file in the jwt-auth folder called api.js. In this file, write the following startup code:

const express = require("express");
const bodyParser = require("body-parser"); 
const app = express();
const PORT = process.env.API_PORT || 8888;
app.use(bodyParser.json());   
app.get("*", (req, res) => {    
  res.sendStatus(404);
}); 
app.listen(PORT, () => {    
  console.log(`Server is running on port ${PORT}.`);
});

Let’s create a new route called '/asset. This will be public route that I had mentioned earlier, and will simply return a status code 200.

app.get("/asset", (req, res) => {
  res.status(200).send("Everybody can see this");
});

The second, secret route will be /asset/secret and it will be secured with a jwtCheck as shown below:

app.get("/asset/secret", jwtCheck, (req, res) => {
  res.status(200).send("Only logged in people can see me");
});

Since the index.js file is set to run on the PORT 8888, we need to set some other PORT for this file. To do that, open the command terminal and run the command:

$ export API_PORT=5555

Even though we have said that the /asset/secret route is secure, we haven’t actually implemented it. To do so, we need to install another middleware library called express-jwt.

$ npm install express-jwt

Then at the top of api.js file, write the require statement for this library.

const expressjwt = require("express-jwt");

We will use this library to define the jwtCheck. We will use jwtCheck to check if the signature matches the one that we got from our authentication server. If you recall, we have named it as “mykey”.

const jwtCheck = expressjwt({    
  secret: "mykey"
});

Run the node api.js command in your terminal. To check if the authentication works as it should, go to POSTMAN and run the GET request on localhost:5000/asset. The response should be Everybody can see this.

Then run the GET request on localhost:5000/asset/secret. What you should get is a big error code that looks something like this:

To solve this, go to the Authentication tab in POSTMAN, and select the Type as Bearer Token. Then enter the value of Token as the one that we had received in the previous sections.

Conclusion

Compared to other web tokens like Simple **Web Tokens (SWTs) **or Security Assertion Markup Language (SAML), **JWT **is much simpler as it is based on **JSON **which is easier to understand than XML.

If we encode the JSON, it will become even more smaller in size than SAML, making it easier to pass in HTML and HTTP environments.

Security wise, SWTs use a single key, whereas both JWT and SAML use a public and private key pair for better authentication.

Talking from a usage point of view, JWTs are used at Internet scale. This means that it is easier to process on the user’s devices, be it laptops or mobile.

Apart from authenctication, JSON Web Token are a great and secure way of transmitting data between multiple parties. The fact that JWTs have signatures makes it easier for everyone to easily identify the sender of information. All you need is the correct key.

Thanks for reading! I hope this post helped you understand how to implement a simple JSON Web Token Authentication in your application. Feel free to comment and ask/suggest anything!

#javascript #web-development #security #json

What is GEEK

Buddha Community

The Complete Guide to JSON Web Tokens
Brandon  Adams

Brandon Adams

1625637060

What is JSON? | JSON Objects and JSON Arrays | Working with JSONs Tutorial

In this video, we work with JSONs, which are a common data format for most web services (i.e. APIs). Thank you for watching and happy coding!

Need some new tech gadgets or a new charger? Buy from my Amazon Storefront https://www.amazon.com/shop/blondiebytes

What is an API?
https://youtu.be/T74OdSCBJfw

JSON Google Extension
https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en

Endpoint Example
http://maps.googleapis.com/maps/api/geocode/json?address=13+East+60th+Street+New+York,+NY

Check out my courses on LinkedIn Learning!
REFERRAL CODE: https://linkedin-learning.pxf.io/blondiebytes
https://www.linkedin.com/learning/instructors/kathryn-hodge

Support me on Patreon!
https://www.patreon.com/blondiebytes

Check out my Python Basics course on Highbrow!
https://gohighbrow.com/portfolio/python-basics/

Check out behind-the-scenes and more tech tips on my Instagram!
https://instagram.com/blondiebytes/

Free HACKATHON MODE playlist:
https://open.spotify.com/user/12124758083/playlist/6cuse5033woPHT2wf9NdDa?si=VFe9mYuGSP6SUoj8JBYuwg

MY FAVORITE THINGS:
Stitch Fix Invite Code: https://www.stitchfix.com/referral/10013108?sod=w&som=c
FabFitFun Invite Code: http://xo.fff.me/h9-GH
Uber Invite Code: kathrynh1277ue
Postmates Invite Code: 7373F
SoulCycle Invite Code: https://www.soul-cycle.com/r/WY3DlxF0/
Rent The Runway: https://rtr.app.link/e/rfHlXRUZuO

Want to BINGE?? Check out these playlists…

Quick Code Tutorials: https://www.youtube.com/watch?v=4K4QhIAfGKY&index=1&list=PLcLMSci1ZoPu9ryGJvDDuunVMjwKhDpkB

Command Line: https://www.youtube.com/watch?v=Jm8-UFf8IMg&index=1&list=PLcLMSci1ZoPvbvAIn_tuSzMgF1c7VVJ6e

30 Days of Code: https://www.youtube.com/watch?v=K5WxmFfIWbo&index=2&list=PLcLMSci1ZoPs6jV0O3LBJwChjRon3lE1F

Intermediate Web Dev Tutorials: https://www.youtube.com/watch?v=LFa9fnQGb3g&index=1&list=PLcLMSci1ZoPubx8doMzttR2ROIl4uzQbK

GitHub | https://github.com/blondiebytes

Twitter | https://twitter.com/blondiebytes

LinkedIn | https://www.linkedin.com/in/blondiebytes

#jsons #json arrays #json objects #what is json #jsons tutorial #blondiebytes

Hollie  Ratke

Hollie Ratke

1596830400

What is JSON Web Token

A JSON Web Token (JWT) is a JSON object that is defined in RFC 7519 as a safe way of transmitting information between two parties. Information in the JWT is digitally-signed, so that it can be verified and trusted.

JWT Properties

  • Less verbose - JWT is compact in size and can be passed in the URL, POST parameter, or HTTP header.
  • Self-contained - JWT carries all of information needed for exchanging information and authentication.
  • Versatile - JWT works in .NET, Python, Node.js, Java, PHP, Ruby, Go, JavaScript, and Haskell.

JWT Use Cases

  • Information Exchange - JWT can be used between two parties to exchange information. JWT is digitally-signed and can be used in a secure public/private key pair. Information is verified using the public key on the other end.
  • Authentication - JWT can contain user information in the payload and can be used in the session to authenticate the user. Once authenticated, users can access protected resources in an application using the JWT included in the request. So, every request will be authenticated by verifying the JWT.

JWT contains three parts: Header, Payload, and Signature which are separated by a dot.

Header.Payload.Signature

Header

The JWT Header consists of 2 parts:

  • The token type (typ): JWT
  • Algorithm used to sign the token (alg)
{  
 "typ" : "JWT",  
 "alg" : "HS256"  
}

Header Algorithm Types:

  • Symmetric Algorithms - This algorithm type uses a single secret key to both sign and verify the JWT token. For example: HMAC algorithms.
  • Asymmetric Algorithms - This algorithm type uses a private key to sign the token and a public key to verify the signature. For example: RSA and ECDSA algorithms.

alg Value

Digital Signature or MAC Algorithm

AlgoDescriptionHS256HMAC using SHA-256 hash algorithmHS384HMAC using SHA-384 hash algorithmHS512HMAC using SHA-512 hash algorithmRS256RSASSA using SHA-256 hash algorithmRS384RSASSA using SHA-384 hash algorithmRS512RSASSA using SHA-512 hash algorithmES256ECDSA using P-256 curve and SHA-256 hash algorithmES384ECDSA using P-384 curve and SHA-384 hash algorithmES512ECDSA using P-521 curve and SHA-512 hash algorithm

The Base64Url-encoded Header**,** which is first part of our JWT, looks like the following:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

Payload

The Payload, also known as the JWT claim, contains all of the information we want to transmit.

Different types of claims can be used to build the Payload:

  • Registered Claim - These claims are optional but recommended as they contain some metadata about the token:

CodeNameDescriptionississuerIdentifies the principal that issued the JWT.subsubjectIdentifies the principal that is the subject of the JWT.audaudienceIdentifies the recipients that the JWT is intended for.expExpiration timeIdentifies the expiration time on or after which the JWT MUST NOT be accepted for processing.nbfNot beforeIdentifies the time before which the JWT MUST NOT be accepted for processing.iatIssue atIdentifies the time at which the JWT was issued.jtiJWT idUnique identifier for the JWT, can be used to prevent the JWT from being replayed.

  • Public Claim - These claims are defined by you, such as user name, and other important information.
  • Private Claim - A producer and consumer may agree to use claim names that are private. These are subject to collision, so use them with caution.

Example Payload:

{  
 "sub": "1234567890",  
 "name": "Frank Emic",  
 "jti": "4b5fcea6-2a5e-4a9d-97f2-3d8631ea2c5a",  
 "iat": 1521191902,  
 "exp": 1521195630  
}

This example contains a combination of registered and public claims. “sub”,”jti”,”iat”, and “exp” are registered claims and “name” is a public claim.

#json #token #web

Spring Security with JSON Web Token and Refresh Token

In this tutorial, you will understand and learn how to generate and sign a JSON Web Token to securely access your RESTful application. This tutorial teaches how to use JWT (JSON Web Token) to embed user roles and permissions to delegate users authorization(what they can and can’t do) in the application. It also dives into defining and creating API, exposing API Endpoints over HTTP, and testing API Endpoints (using an HTTP client - Postman).

Source Code:
https://github.com/getarrays/userservice

Intro 0:00
What is JWT(Json Web Token) 1:00
Authentication and Authorization 05:00
Security with JWT 08:02
Domain Models 11:02
Repository 20:12
Service and Implementation - Part 1 22:41
Service and Implementation - Part 2 30:34
API Resource - Part 1 33:01
API Resource - Part 2 33:01
Adding Data - Part 2 46:48
Security Configuration 52:02
Authentication Filter Part 1 01:03:13
Authentication Filter Part 2 01:11:31
Authentication Filter Part 3 01:19:42
Course Promo 1:31:10
Course App Demo 01:33:22
Authorization Filter Part 1 - 01:42:53
Authorization Filter Part 2 - 01:53:43
Refresh Token 01:58:56

#json web token #jwt #token #spring

Ashish parmar

Ashish parmar

1627043546

Evolution in Web Design: A Case Study of 25 Years - Prismetric

The term web design simply encompasses a design process related to the front-end design of website that includes writing mark-up. Creative web design has a considerable impact on your perceived business credibility and quality. It taps onto the broader scopes of web development services.

Web designing is identified as a critical factor for the success of websites and eCommerce. The internet has completely changed the way businesses and brands operate. Web design and web development go hand-in-hand and the need for a professional web design and development company, offering a blend of creative designs and user-centric elements at an affordable rate, is growing at a significant rate.

In this blog, we have focused on the different areas of designing a website that covers all the trends, tools, and techniques coming up with time.

Web design
In 2020 itself, the number of smartphone users across the globe stands at 6.95 billion, with experts suggesting a high rise of 17.75 billion by 2024. On the other hand, the percentage of Gen Z web and internet users worldwide is up to 98%. This is not just a huge market but a ginormous one to boost your business and grow your presence online.

Web Design History
At a huge particle physics laboratory, CERN in Switzerland, the son of computer scientist Barner Lee published the first-ever website on August 6, 1991. He is not only the first web designer but also the creator of HTML (HyperText Markup Language). The worldwide web persisted and after two years, the world’s first search engine was born. This was just the beginning.

Evolution of Web Design over the years
With the release of the Internet web browser and Windows 95 in 1995, most trading companies at that time saw innumerable possibilities of instant worldwide information and public sharing of websites to increase their sales. This led to the prospect of eCommerce and worldwide group communications.

The next few years saw a soaring launch of the now-so-famous websites such as Yahoo, Amazon, eBay, Google, and substantially more. In 2004, by the time Facebook was launched, there were more than 50 million websites online.

Then came the era of Google, the ruler of all search engines introducing us to search engine optimization (SEO) and businesses sought their ways to improve their ranks. The world turned more towards mobile web experiences and responsive mobile-friendly web designs became requisite.

Let’s take a deep look at the evolution of illustrious brands to have a profound understanding of web design.

Here is a retrospection of a few widely acclaimed brands over the years.

Netflix
From a simple idea of renting DVDs online to a multi-billion-dollar business, saying that Netflix has come a long way is an understatement. A company that has sent shockwaves across Hollywood in the form of content delivery. Abundantly, Netflix (NFLX) is responsible for the rise in streaming services across 190 countries and meaningful changes in the entertainment industry.

1997-2000

The idea of Netflix was born when Reed Hastings and Marc Randolph decided to rent DVDs by mail. With 925 titles and a pay-per-rental model, Netflix.com debuts the first DVD rental and sales site with all novel features. It offered unlimited rentals without due dates or monthly rental limitations with a personalized movie recommendation system.

Netflix 1997-2000

2001-2005

Announcing its initial public offering (IPO) under the NASDAQ ticker NFLX, Netflix reached over 1 million subscribers in the United States by introducing a profile feature in their influential website design along with a free trial allowing members to create lists and rate their favorite movies. The user experience was quite engaging with the categorization of content, recommendations based on history, search engine, and a queue of movies to watch.

Netflix 2001-2005 -2003

2006-2010

They then unleashed streaming and partnering with electronic brands such as blu-ray, Xbox, and set-top boxes so that users can watch series and films straight away. Later in 2010, they also launched their sophisticated website on mobile devices with its iconic red and black themed background.

Netflix 2006-2010 -2007

2011-2015

In 2013, an eye-tracking test revealed that the users didn’t focus on the details of the movie or show in the existing interface and were perplexed with the flow of information. Hence, the professional web designers simply shifted the text from the right side to the top of the screen. With Daredevil, an audio description feature was also launched for the visually impaired ones.

Netflix 2011-2015

2016-2020

These years, Netflix came with a plethora of new features for their modern website design such as AutoPay, snippets of trailers, recommendations categorized by genre, percentage based on user experience, upcoming shows, top 10 lists, etc. These web application features yielded better results in visual hierarchy and flow of information across the website.

Netflix 2016-2020

2021

With a sleek logo in their iconic red N, timeless black background with a ‘Watch anywhere, Cancel anytime’ the color, the combination, the statement, and the leading ott platform for top video streaming service Netflix has overgrown into a revolutionary lifestyle of Netflix and Chill.

Netflix 2021

Contunue to read: Evolution in Web Design: A Case Study of 25 Years

#web #web-design #web-design-development #web-design-case-study #web-design-history #web-development

Hello Jay

Hello Jay

1600500567

How To Debug JSON Web Tokens (JWTs)

Many modern web applications, both client-side and server-side, use JSON Web Tokens (JWTs) for authentication, which is an excellent approach. However, when things don’t work, it can be tricky to work out why.

This post aims to give you some tactics for understanding and correcting problems with JWTs. If you’re just getting started, check out the  documentation on working with JWTs and our APIs first.

Does Your JSON Web Token Look Plausible?

Sometimes the problem is as simple as knowing whether you even passed the right value into the right place, the equivalent to “is it plugged in?” question.

So, add a little debugging to your code to output the JWT somewhere you can see, such as your error log or console.

Then take a look for the following:

  • Does this look like a token? It should be three sets of garbled-looking alphanumeric strings (technically, upper and lower case characters, numeric digits, + and / are permitted, with = used for padding), separated by dots.
  • Is there whitespace around it, including a newline at the end? Pesky, errant whitespaces can trip up some tools.
  • Is it there at all? I have mistyped a variable name and regenerated the token a few times before realising that the problem is me, not the token.

If the token passes visual inspection, then we need to get out some more specific tools.

#json #json web tokens #jwts #security #tips and tricks