<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ JSON Web Tokens - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ JSON Web Tokens - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 07 May 2026 09:28:00 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/json-web-tokens/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Use JSON Web Tokens for Secure Authentication in Flask Applications ]]>
                </title>
                <description>
                    <![CDATA[ Passwords, credit card information, personal identification numbers (PINs) – these are all critical assets used for authorization and authentication. This means they need to be protected from unauthorized users. As developers, we are tasked with safe... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/jwt-authentication-in-flask/</link>
                <guid isPermaLink="false">66c37432ad70110156766fe4</guid>
                
                    <category>
                        <![CDATA[ authentication ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Flask Framework ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JSON Web Tokens ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JWT ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Yemi Ojedapo ]]>
                </dc:creator>
                <pubDate>Wed, 17 Apr 2024 16:29:02 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/04/pexels-soumil-kumar-735911--1-.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Passwords, credit card information, personal identification numbers (PINs) – these are all critical assets used for authorization and authentication. This means they need to be protected from unauthorized users.</p>
<p>As developers, we are tasked with safeguarding these sensitive bits of info, and it's important to implement strong secure measures in our applications. </p>
<p>Now, there are many authentication mechanisms available for securing data, like OAuth, OpenID Connect, and JSON Web Tokens (JWTs).</p>
<p>In this article, I'll show you how to use JWTs when securing information in APIs by integrating JWT-based authentication in a Flask application. </p>
<p>Here's what this article will cover:</p>
<ul>
<li><a class="post-section-overview" href="#heading-what-is-a-json-web-token">What is a JSON Web Token?</a></li>
<li><a class="post-section-overview" href="#heading-how-do-jwts-work">How Do JWTs Work?</a></li>
<li><a class="post-section-overview" href="#heading-how-to-use-json-web-tokens-to-authenticate-flask-applications">How to Use JSON Web Tokens to Authenticate Flask Applications</a>  </li>
<li><a class="post-section-overview" href="#heading-1-install-the-dependencies">Install dependencies</a>  </li>
<li><a class="post-section-overview" href="#heading-2-create-a-database-and-user-model">Create a database and user model</a>  </li>
<li><a class="post-section-overview" href="#3-configure-the-application-for-jwt-authorization">Configure the application for JWT authentication</a>  </li>
<li><a class="post-section-overview" href="#heading-4-create-protected-routes">Create protected routes</a>  </li>
<li><a class="post-section-overview" href="#heading-5-create-a-login-page">Create a Login Function</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along with this tutorial you will need:</p>
<ul>
<li>An understanding of HTTP Methods</li>
<li>An understanding of how to create APIs in Flask</li>
<li>VS Code (or other similar) editor</li>
<li>A terminal</li>
</ul>
<h2 id="heading-what-is-a-json-web-token">What is a JSON Web Token?</h2>
<p>JSON Web Tokens, or JWTs, are an authentication mechanism used to securely transmit information between a client and a server in JSON format. </p>
<p>This information can be verified and trusted because it is digitally signed with the <a target="_blank" href="https://xilinx.github.io/Vitis_Libraries/security/2020.1/guide_L1/internals/hmac.html">HMAC algorithm</a> or a public/private key pair using <a target="_blank" href="https://en.wikipedia.org/wiki/RSA_(cryptosystem)">RSA</a> or <a target="_blank" href="https://en.wikipedia.org/wiki/Elliptic_Curve_Digital_Signature_Algorithm">ECDSA</a>. </p>
<p>The tokens are encoded into three parts, each divided by a period, like this:</p>
<pre><code>Header.Payload.Signature
</code></pre><ul>
<li><strong>Header:</strong> This defines the type of token (JWT) and the signing algorithm used.</li>
<li><strong>Payload:</strong> This carries user-specific data like user ID, username, roles, and any additional claims you want to include. This payload is encoded in Base64 for maximum security.</li>
<li><strong>Signature:</strong> This is a hashed combination of the header, the payload, and the server's secret key. It ensures the token's integrity and that any modifications to the token will be detected.</li>
</ul>
<h2 id="heading-how-do-jwts-work">How Do JWTs Work?</h2>
<p>To understand how JWTs work, you need to know what the tokens are meant to do. JWTs are not created to hide data but to ensure that the data being sent is authenticated. This is why the JWT is signed and encoded, not encrypted.</p>
<p>A JWT acts as a stateless means of transmitting data from a client to a server. This means that it doesn't store any session object in the browser, so the browser doesn't maintain a session state between requests. </p>
<p>Instead, JWTs use a token that is sent in a request header each time a request is made. This token confirms that the token sent is authenticated and is allowed access to make that request.  </p>
<p>Let's look at how this happens:</p>
<ol>
<li>A user attempts to log in and sends a username and password to be verified by the server.</li>
<li>The verification function carries out a check to see if there's a match in the database.</li>
<li>A JWT is then generated by the server once the user is successfully authenticated (logged in) using their information (payload), such as user ID or username, and signs it using a secret key.</li>
<li>The generated JWT is sent along as a bearer token with every request header to check if the user is authenticated to make that request.</li>
</ol>
<h2 id="heading-how-to-use-json-web-tokens-to-authenticate-flask-applications">How to Use JSON Web Tokens to Authenticate Flask Applications</h2>
<p>To demonstrate how you can implement JWT authentication in Flask, we'll create a simple application that uses JWT for handling login functions and accessing protected routes.</p>
<h3 id="heading-1-install-the-dependencies">1. Install the dependencies</h3>
<p>Run this command to install the dependencies we'll need</p>
<pre><code>pip install flask flask-bcrypt Flask-JWT-Extended
</code></pre><p>Next, make sure you import the dependencies and initialize your Flask application with this code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, jsonify, session, request, redirect, url_for
<span class="hljs-keyword">from</span> flask_jwt_extended <span class="hljs-keyword">import</span> JWTManager, create_access_token, jwt_required, get_jwt_identity, get_jwt


app = Flask(__name__)

////WRITE MAIN CODE HERE


<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    <span class="hljs-keyword">with</span> app.app_context():
        app.run(debug=<span class="hljs-literal">True</span>)
</code></pre>
<h3 id="heading-2-create-a-database-and-user-model">2. Create a database and User Model</h3>
<p>To do this, we'll use SQL-Alchemy, which is a Python SQL toolkit that makes it less complex to use SQL in Python scripts. </p>
<p>To set up SQL Alchemy in your application, follow these steps:</p>
<p>First, open your terminal or command prompt and enter the following command:</p>
<pre><code>pip install sqlalchemy
</code></pre><p>This command installs SQLAlchemy in your Python environment, making it available in your project directory.</p>
<p>Next, configure your application to make use of your preferred Database Management System (DBMS). This tutorial will use the SQlite3 DBMS as it doesn't require a separate server:</p>
<pre><code>app.config[<span class="hljs-string">'SQLALCHEMY_DATABASE_URI'</span>] = <span class="hljs-string">'sqlite:///site.db'</span>
</code></pre><p>This code snippet instructs Flask-SQLAlchemy to create and use the <code>site.db</code> file in your project directory as the SQLite database for the application.</p>
<p>Then initialize the database in your application:</p>
<pre><code>db = SQLAlchemy(app)
</code></pre><p>This instance of the database acts as a bridge between the application and the database.</p>
<p>Now create the User Model where we'll store the user's details in this tutorial:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span>(<span class="hljs-title">db</span>.<span class="hljs-title">Model</span>, <span class="hljs-title">UserMixin</span>):
    <span class="hljs-title">id</span> </span>= db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(<span class="hljs-number">20</span>), unique=True, nullable=False)
    password = db.Column(db.String(<span class="hljs-number">80</span>), nullable=False)
    is_active = db.Column(db.Boolean(), <span class="hljs-keyword">default</span>=True)
    cart = db.Column(<span class="hljs-built_in">JSON</span>, nullable=True, <span class="hljs-keyword">default</span>=list)  # Make cart nullable

    # Define the relationship between User and CartProducts
    cart_products = relationship(<span class="hljs-string">'CartProducts'</span>, backref=<span class="hljs-string">"user"</span>, lazy=<span class="hljs-string">"dynamic"</span>)
    # Define the relationship between User and Wishlists
    wishlists = db.relationship(<span class="hljs-string">'Wishlists'</span>, backref=<span class="hljs-string">'user'</span>, lazy=True)

    def __repr__(self):
        <span class="hljs-keyword">return</span> f<span class="hljs-string">'&lt;User {self.username}&gt;'</span>
</code></pre><p> <strong>Note:</strong> You can create other models using the same syntax to represent different data entities in your application.</p>
<h3 id="heading-3-configure-the-application-for-jwt-authentication">3. Configure the application for JWT Authentication</h3>
<p>To implement JWT authentication in your Flask application, import the necessary libraries and set up the appropriate configurations with this code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> flask <span class="hljs-keyword">import</span> Flask, jsonify, request
<span class="hljs-keyword">from</span> flask_sqlalchemy <span class="hljs-keyword">import</span> SQLAlchemy
<span class="hljs-keyword">from</span> flask_jwt_extended <span class="hljs-keyword">import</span> JWTManager, create_access_token, jwt_required

app = Flask(__name__)

<span class="hljs-comment"># Configuration</span>
app.config[<span class="hljs-string">'SECRET_KEY'</span>] = <span class="hljs-string">'your_strong_secret_key'</span>
app.config[<span class="hljs-string">"JWT_SECRET_KEY"</span>] = <span class="hljs-string">'your_jwt_secret_key'</span>
app.config[<span class="hljs-string">'JWT_TOKEN_LOCATION'</span>] = [<span class="hljs-string">'headers'</span>]

<span class="hljs-comment"># Database Initialization</span>
db = SQLAlchemy(app)

<span class="hljs-comment"># JWT Initialization</span>
jwt = JWTManager(app)

<span class="hljs-comment"># Rest of the application code (routes, etc.)</span>
</code></pre>
<p>This code snippet imports the following components needed for our application:</p>
<ul>
<li><strong>app.config['SECRET_KEY']</strong> sets the Flask application's secret key which is used to securely sign session cookies and other security-related needs.</li>
<li><strong>app.config['JWT_SECRET_KEY']</strong> sets the secret key used to encode and decode JWTs in for Flask-JWT operations.</li>
<li><strong>app.config['JWT_TOKEN_LOCATION']</strong> specifies where the application should look for the JWT. Here it's set to look in the HTTP headers.</li>
</ul>
<p>Once we've set this up, we can create the endpoints and routes that we intend to protect.</p>
<h3 id="heading-4-create-protected-routes">4. Create protected routes</h3>
<p>Protected routes are the pages that we intend to keep hidden from unauthorized users. </p>
<p>For example, let's assume we are trying to get into a venue that's exclusive to members of a society. But a guard is securing the venue from "unauthorized users" like us. In this situation, we are the application's users, the venue is the URL we are protecting, and the guard protecting the venue is a <strong><code>@jwt_required</code></strong> decorator.</p>
<p>The <strong><code>@jwt_required</code></strong> decorator is used to protect specific routes that require authentication. This decorator will confirm that there's a JWT access token in the request headers before allowing access to the page:</p>
<pre><code class="lang-python"><span class="hljs-meta">@app.route('/get_name', methods=['GET'])</span>
<span class="hljs-meta">@jwt_required()</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_name</span>():</span>
    <span class="hljs-comment"># Extract the user ID from the JWT</span>
    user_id = get_jwt_identity()
    user = User.query.filter_by(id=user_id).first()

    <span class="hljs-comment"># Check if user exists</span>
    <span class="hljs-keyword">if</span> user:
        <span class="hljs-keyword">return</span> jsonify({<span class="hljs-string">'message'</span>: <span class="hljs-string">'User found'</span>, <span class="hljs-string">'name'</span>: user.name})
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> jsonify({<span class="hljs-string">'message'</span>: <span class="hljs-string">'User not found'</span>}), <span class="hljs-number">404</span>
</code></pre>
<p>In this code snippet, we created a function that returns the name of the user after authentication. If the token is missing, invalid, or expired, the request will be denied, and typically, the server will return an HTTP <strong>401</strong> Unauthorized status.</p>
<h3 id="heading-5-create-a-login-page">5. Create a Login Page</h3>
<p>In this endpoint, we'll create a function that accepts username and password credentials from the client request (for example, form data) and compares the credentials gotten from the user with the user data in the database. If there's a match, a JWT access token will be generated containing the user's information.</p>
<pre><code class="lang-python"><span class="hljs-meta">@app.route('/login', methods=['POST'])</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">login</span>():</span>
    data = request.get_json()
    username = data[<span class="hljs-string">'username'</span>]
    password = data[<span class="hljs-string">'password'</span>]
    print(<span class="hljs-string">'Received data:'</span>, username , password)

    user = User.query.filter_by(username=username).first()

    <span class="hljs-keyword">if</span> user <span class="hljs-keyword">and</span> bcrypt.check_password_hash(user.password, password):
        access_token = create_access_token(identity=user.id)
        <span class="hljs-keyword">return</span> jsonify({<span class="hljs-string">'message'</span>: <span class="hljs-string">'Login Success'</span>, <span class="hljs-string">'access_token'</span>: access_token})
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> jsonify({<span class="hljs-string">'message'</span>: <span class="hljs-string">'Login Failed'</span>}), <span class="hljs-number">401</span>
</code></pre>
<p>In this example, the function checks the user's credentials against the database using bcrypt for secure password verification when a POST request is received. If the credentials are valid, the server generates a JWT for the user, allowing them to access protected routes.</p>
<p>Here's an example of a React form sending a POST request to the login endpoint:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">"axios"</span>;
<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> Footer <span class="hljs-keyword">from</span> <span class="hljs-string">"./Footer"</span>;
<span class="hljs-comment">// import "./Login.css";</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Login</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [password, setPassword] = useState(<span class="hljs-string">""</span>);
  <span class="hljs-keyword">const</span> [username, setUsername] = useState(<span class="hljs-string">""</span>);

  <span class="hljs-keyword">const</span> handleLogin = <span class="hljs-keyword">async</span> (event) =&gt; {
    event.preventDefault();
    <span class="hljs-keyword">const</span> data = {
      <span class="hljs-attr">username</span>: username,
      <span class="hljs-attr">Password</span>: password,
    };

    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.post(<span class="hljs-string">"http://localhost:5000/login"</span>, {
        username,
        password,
      });
      <span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">"access_token"</span>, response.data.access_token);
      <span class="hljs-comment">// Redirect to protected route</span>
      alert(<span class="hljs-string">"Login successful"</span>);
    } <span class="hljs-keyword">catch</span> (error) {
      <span class="hljs-built_in">console</span>.error(error);
      <span class="hljs-comment">// Display error message to user</span>
    }
  };

  <span class="hljs-keyword">const</span> handleUsernameChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setUsername(event.target.value);
  };

  <span class="hljs-keyword">const</span> handlePasswordChange = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    setPassword(event.target.value);
  };

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> &gt;</span>

          <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"post"</span> &gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
                <span class="hljs-attr">id</span>=<span class="hljs-string">""</span>
                <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Username"</span>
                <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span>
                <span class="hljs-attr">required</span>
                <span class="hljs-attr">value</span>=<span class="hljs-string">{username}</span>
                <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleUsernameChange}</span>
              /&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
                <span class="hljs-attr">id</span>=<span class="hljs-string">""</span>
                <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Your email"</span>
              /&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
                <span class="hljs-attr">type</span>=<span class="hljs-string">"password"</span>
                <span class="hljs-attr">required</span>
                <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Your Password"</span>
                <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span>
                <span class="hljs-attr">value</span>=<span class="hljs-string">{password}</span>
                <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handlePasswordChange}</span>
              /&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleLogin}</span>&gt;</span>
            Log In
          <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );

}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Login;
</code></pre>
<p>In this React component, we provided a login form that uses Axios to send a POST request to the login endpoint. It manages username and password inputs using React's <code>useState</code> hook and submits these values once the form is submitted. </p>
<p>If the login is successful, it stores a JWT in local Storage. This allows the client-side application to retrieve the token easily when making authenticated requests to the server.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/04/jwtDemo-1.gif" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we've learned how to secure APIs with JSON Web Tokens in Flask. We covered the basics of JWTs, how they work, and provided a step-by-step process for implementing this method of authentication. This included everything from installing necessary dependencies to creating user models and protecting routes. </p>
<p>You can build upon this foundation, such as by adding refresh tokens, integrating with third-party OAuth providers, or handling more complex user permissions.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Implement Tokenization using JWT and Django Rest Framework ]]>
                </title>
                <description>
                    <![CDATA[ When I was a young girl, we used to have sports competitions like running a hundred meters, relays, swimming, and basketball games.  My strengths were swimming and basketball. I went home with many gifts or, as my school's game master said, a token o... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-jwt-and-django-rest-framework-to-get-tokens/</link>
                <guid isPermaLink="false">66ba555237218559f94f2076</guid>
                
                    <category>
                        <![CDATA[ Django ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JSON Web Tokens ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JWT ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Tokenization ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Velda Kiara ]]>
                </dc:creator>
                <pubDate>Thu, 23 Feb 2023 15:53:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2023/01/Purple-Colorful-Tech-22-YouTube-Channel-Art.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>When I was a young girl, we used to have sports competitions like running a hundred meters, relays, swimming, and basketball games. </p>
<p>My strengths were swimming and basketball. I went home with many gifts or, as my school's game master said, a <strong>token of appreciation</strong>.</p>
<p>A token is a secure form used to transmit data between two parties. The medals I got from the competitions hold a lot of value for me, and if I gave them to someone else, they would merely be trinkets.</p>
<p>JavaScript Object Notation (JSON) is a format used to present structured data based on JavaScript syntax. We use it to transmit data in web applications by sending the data from the server to the client's display.</p>
<p>JWT (JSON Web Token) is a form of transmitting a JSON object as information between parties. Let's learn more about what JWTs are and how they work.</p>
<h2 id="heading-the-importance-of-jwts">The Importance of JWTs</h2>
<p>JWTs are important for two main reasons:</p>
<p><strong>Authorization</strong>: in our competitions, we had to present our school identification cards for verification before getting our medals. </p>
<p>Our school IDs acted like log in requests in applications. These requests, in apps, contain a JWT that allows users to get permission to access any resources that are accessible with that token.</p>
<p><strong>Information exchange</strong>: my medals were a badge of honor and a way to get a certificate signed and stamped by our games master for legitimacy. </p>
<p>We use JWTs to exchange information in cases where they are signed – for example using public-private key pairs to make sure that the integrity of the information is not compromised since the payload and header are used to compute signatures.</p>
<h2 id="heading-how-do-jwts-work">How Do JWTs Work?</h2>
<p>A JWT is an authorization token that is included in requests. Here's an example of what one looks like:</p>
<pre><code class="lang-python">eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjczNTI3ODMzLCJpYXQiOjE2NzM1Mjc0MzAsImp0aSI6IjNkMGRkMGZiZjA5ZjRmZWU4MTZmMGQyOTQ5OWU3ZmFmIiwidXNlcl9pZCI6IjFmYTBiMGJkLWY4MmMtNDQzNy1iMmViLTMwOTYzMGZkNzQ2NiJ9.-swqFh4MCecycmodQfO8ZmfsDJ3DqoZBsdNzEWhfzhA
</code></pre>
<p>You can get a JWT through logging in with a username and password. In exchange the server returns an access and refresh token in the form of a JWT. The tokens access resources on the server.</p>
<p>The lifetimes of the access and refresh tokens vary since access tokens last for five minutes or less while the refresh tokens can last for 24 hours. But you can customize the timelines of both types of tokens.</p>
<p>If the access token expires, the client uses the refresh token to summon a new access token from the server. Once the refresh token expires, the user must log in again with their username and password to get a new pair of tokens. </p>
<p>It works this way to prevent damage that can occur when a token is compromised and to prevent unauthorized access.</p>
<h3 id="heading-different-parts-of-a-jwt">Different parts of a JWT</h3>
<p>JWTs hold information in three parts, as you can see in the following code blocks:</p>
<pre><code class="lang-python">header.payload.signature
</code></pre>
<pre><code class="lang-python">header = eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9F5
payload = eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNTQzODI4NDMxLCJqdGkiOiI3ZjU5OTdiNzE1MGQ0NjU3OWRjMmI0OTE2NzA5N2U3YiIsInVsztZXJfaWQiOjF9
signature = Ju70kdcaHKn1Qaz8H42zrOYk0Jx9kIciuhkTn9Xx7vhikY
</code></pre>
<p>The above JWT is encoded using <a target="_blank" href="https://en.wikipedia.org/wiki/Base64">Base64</a>. Once decoded, the information will include something similar to the following parts:</p>
<h4 id="heading-header">Header</h4>
<p>The header contains:</p>
<ul>
<li>type: the specification that the token is a JWT</li>
<li>algorithm: the signing algorithm used to sign said token</li>
</ul>
<p>Algorithms that are used to sign include <a target="_blank" href="https://www.geeksforgeeks.org/rsa-algorithm-cryptography/">RSA</a>, <a target="_blank" href="https://www.geeksforgeeks.org/hmac-algorithm-in-computer-network/">HMAC</a>, or <a target="_blank" href="https://www.n-able.com/blog/sha-256-encryption#:~:text=The%20SHA%2D256%20algorithm%20is,that%20is%20256%20bits%20long.">SHA256</a>. The signatures for the tokens serve two purposes – integrity and authenticity.</p>
<p>An example of a header with the algorithm and type is as shown below:</p>
<pre><code class="lang-python">{
  <span class="hljs-string">"alg"</span>: <span class="hljs-string">"HS256"</span>,
  <span class="hljs-string">"typ"</span>: <span class="hljs-string">"JWT"</span>
}
</code></pre>
<h4 id="heading-payload">Payload</h4>
<p>The payload contains the intended messages which are commonly known as claims and metadata, as well as any other information.</p>
<p>There are three types of claims:</p>
<ol>
<li>Registered claims: they include exp (expiration time), iss (issuer), sub (subject) and aud (audience). They are highly recommended since they provide information on the use and condition of use of the token.</li>
<li>Public claims: these are claims that are unique to avoid collisions with other services that use JWT. </li>
<li>Private claims: these are claims that are used specifically between two parties that understand the meaning and use. Like the example of my medals, my games master and I understood the value.</li>
</ol>
<p>Below is an example of what a payload looks like.</p>
<pre><code class="lang-python">{
  <span class="hljs-string">"token_type"</span>: <span class="hljs-string">"access"</span>,
  <span class="hljs-string">"exp"</span>: <span class="hljs-number">1543828431</span>,
  <span class="hljs-string">"jti"</span>: <span class="hljs-string">"7f5997b7150d46579dc2b49167097e7b"</span>,
  <span class="hljs-string">"user_id"</span>: <span class="hljs-number">4</span>
}
</code></pre>
<ul>
<li><code>token_type</code> is a label that shows what kind of token this is. Case in point, it's an <code>access token</code>.</li>
<li><code>exp</code> stands for expiration. It's the time the token will stop working – in this case the number represents date and time in Unix time.</li>
<li><code>jti</code> stands for <code>JWT ID</code>. It's a unique identifier for this specific token. The ID is used to keep track of which tokens have been used, to prevent use of the same token more than once.</li>
<li><code>user_id</code>:  is an identifier of the user this token belongs to. In this case, the number 4 is the user identification.</li>
</ul>
<h4 id="heading-signature">Signature</h4>
<p>The signature verifies that information is only accessed by authorized people. It is issued by the JWT backend using base64 + payload +SECRET_KEY. </p>
<p>The signature is verified for each request. To validate the signature, you use the SECRET_KEY. Remember the purpose of having it called SECRET_KEY is so that it is secret. </p>
<p>Now let's see how JWTs work in practice with an example.</p>
<h2 id="heading-project-setup">Project Setup</h2>
<p>To illustrate how JWTs work, I will use the <a target="_blank" href="https://django-rest-framework-simplejwt.readthedocs.io/en/latest/">simple JWT</a>, which is a JSON Web Token authentication plugin for Django Rest Framework (DRF). </p>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>To follow along, you should have some prior knowledge of HTML files and how to set up a Django project. You should also be familiar with what an API (Application Programming Interface) is. </p>
<p>You will also need to have a Django project already setup. You could name it <code>tokenization</code> also add an app called <code>access</code>. </p>
<p>Once your app and project are set up, you are good to go. </p>
<h3 id="heading-simple-jwt-installation">Simple JWT Installation</h3>
<p>As mentioned, I will be using the <code>simple JWT</code> which provides JWT authentication for the Django Rest Framework (DRF).  </p>
<p>DRF is a third-party package for Django used as a toolkit for building Web API's. It provides a seamless experience while you build, test, debug and maintain RESTful APIs using in Django. </p>
<p>RESTful APIs (Representational State Transfer APIs) are a type of web API that allow communication between different applications over the internet in a fast, reliable, and scalable way.</p>
<p>RESTful APIs are stateless. This means that requests contain information to finalize the request, and the server does not need to remember the history of previous requests.</p>
<p>To install <code>simple JWT</code>, use the command below in your terminal:</p>
<pre><code class="lang-python">pip install djangorestframework_simplejwt
</code></pre>
<h3 id="heading-how-to-set-authentication-to-simple-jwt">How to Set Authentication to Simple JWT</h3>
<p>Go to your project (tokenization), and in the <code>settings.py</code> file, add the following code to configure the REST framework to use simple JWT for authentication:</p>
<pre><code class="lang-python">REST_FRAMEWORK = {
    <span class="hljs-string">'DEFAULT_AUTHENTICATION_CLASSES'</span>: [
        <span class="hljs-string">'rest_framework_simplejwt.authentication.JWTAuthentication'</span>,
    ],
}
</code></pre>
<p>The code above specifies the default authentication class to be used for all API views in the application.</p>
<p><code>DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ]</code> sets the default authentication class to be  <code>JWTAuthentication</code> from the <code>rest_framework_simplejwt</code> package. This means that all API views in the project will use JWT authentication by default.</p>
<h3 id="heading-how-to-define-uniform-resource-locator-patterns">How to Define Uniform Resource Locator Patterns</h3>
<p>In your project (tokenization), create a file (if you have not created one yet) named<br><code>urls.py</code> . Then add the following code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path
<span class="hljs-keyword">from</span> rest_framework_simplejwt <span class="hljs-keyword">import</span> views <span class="hljs-keyword">as</span> jwt_views

urlpatterns = [
    path(<span class="hljs-string">'api/token/'</span>, jwt_views.TokenObtainPairView.as_view(), name=<span class="hljs-string">'token_obtain_pair'</span>),
    path(<span class="hljs-string">'api/token/refresh/'</span>, jwt_views.TokenRefreshView.as_view(), name=<span class="hljs-string">'token_refresh'</span>),
]
</code></pre>
<p>The <code>path</code> function creates a new URL pattern and maps it to the specified view.</p>
<p>The URL (Uniform Resource Locator) path <code>/api/token/</code> is mapped to the view <code>jwt_views.TokenObtainPairView.as_view()</code>. The <code>as_view()</code>method converts the class-based view to a function-based view used in routing. The <code>name</code> parameter makes it easy to refer to the URL pattern in other parts of your code. </p>
<p>We have now created an endpoint for obtaining JWT tokens. If a request is made to the endpoint, <code>TokenObtainPairView</code>, <code>view</code> handles the request and returns a JWT token in the response for authentication.</p>
<h3 id="heading-how-to-customize-the-token-timelines">How to Customize the Token Timelines</h3>
<p>To customize the timeline of the tokens, first add the <code>rest_framework_simplejwt</code> in your installed apps section in the project (tokenization) under the <code>settings.py</code> file. The purpose for adding the <code>rest_framework_simplejwt</code> is for configuration. </p>
<p>To add the timeline we want, we will first create a dictionary called <code>SIMPLE_JWT</code>. Then we'll create variables to hold timelines for the access and refresh token. </p>
<p>The code snippet below shows how to set up the timelines for the tokens:</p>
<pre><code class="lang-python">INSTALLED_APPS = [
    <span class="hljs-comment">#other files</span>
    <span class="hljs-string">'rest_framework_simplejwt'</span>,
]

SIMPLE_JWT = {
    <span class="hljs-string">'ACCESS_TOKEN_LIFETIME'</span>: timedelta(minutes=<span class="hljs-number">5</span>),
    <span class="hljs-string">'REFRESH_TOKEN_LIFETIME'</span>: timedelta(days=<span class="hljs-number">1</span>),
}
</code></pre>
<p>Before you use the <code>timedelta</code> you will need to import it like this: <code>python from datetime import timedelta</code>.</p>
<h3 id="heading-visual-interaction-of-the-api">Visual Interaction of the API</h3>
<p>In this section, we will use the Django Rest Framework web interface to access the endpoints.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-13-at-10.55.14.png" alt="Image" width="600" height="400" loading="lazy">
<em>Testing tokenization</em></p>
<p>The access and refresh tokens are highlighted in red, as shown above. To get the tokens for a user, you need to input the correct password and username for an existing user.</p>
<p> Use a refresh token through this endpoint for an access token: <code>/api/token/refresh/</code> </p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-13-at-10.55.53.png" alt="Image" width="600" height="400" loading="lazy">
<em>Refresh token</em></p>
<p>A refresh token gets an access token without the user using their login credentials to extend the user's session. This provides a seamless user experience and improves security by reducing the number of times a user has to key in their credentials.</p>
<h3 id="heading-how-to-add-a-homepage">How to Add a Homepage</h3>
<p>If you want to create a visually appealing interface, you can build a custom homepage to replace the current display of the API endpoints and error messages.</p>
<p>To add a homepage to your Django project, follow these steps:</p>
<ol>
<li>Create a <code>templates</code> folder in your application (access). Then, add a <code>index.html</code> file inside.</li>
<li>Create a <code>static</code> folder in your application (access) and add a <code>img</code> folder inside.</li>
<li>In this case, I wanted to display an image, so I added the <code>me.png</code> in the img folder.</li>
<li>Add the code below to your <code>html</code> file:</li>
</ol>
<pre><code class="lang-html">{% load static %}
<span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span><span class="css">
        <span class="hljs-selector-tag">body</span> {
            <span class="hljs-attribute">background-image</span>: <span class="hljs-built_in">url</span>(<span class="hljs-string">"{% static 'img/me.png' %}"</span>);
            <span class="hljs-attribute">background-size</span>: cover;
        }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>You will notice that we needed to add <code>{% load static %}</code> at the top of the file for proper styling and functioning of the site. <code>{% load static %}</code> serves files like stylesheets(CSS), scripts(JS), and images to your HTML templates to provide the user with a seamless experience while viewing your site.</p>
<h3 id="heading-how-to-define-the-url-patterns-for-your-home-page">How to Define the URL Patterns For Your Home Page</h3>
<p>In your app's (access) <code>urls.py</code> file (create one if you do not have it) add this:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path
<span class="hljs-keyword">from</span> django.views.generic <span class="hljs-keyword">import</span> TemplateView

app_name=<span class="hljs-string">'access'</span>

urlpatterns=[
path(<span class="hljs-string">''</span>, TemplateView.as_view(template_name=<span class="hljs-string">'home.html'</span>), name=<span class="hljs-string">'home'</span>),

]
</code></pre>
<p>In your project's (tokenization) <code>settings.py</code> file, add the following code so that the static files are served:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Static files settings</span>
STATIC_ROOT = os.path.join(BASE_DIR, <span class="hljs-string">'static'</span>)
STATIC_URL = <span class="hljs-string">'/static/'</span>
STATICFILES_DIRS = [os.path.join(BASE_DIR, <span class="hljs-string">'access/static'</span>)]
</code></pre>
<p>Once you run the server, your home page should be like this:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2023/01/Screenshot-2023-01-13-at-10.54.54.png" alt="Image" width="600" height="400" loading="lazy">
<em>home page</em></p>
<h2 id="heading-bugs-and-solutions">Bugs and Solutions</h2>
<p>At some point, I may have deleted the <code>migrations</code> file which deleted some of the data I had. This caused the following error <code>django.db.utils.OperationalError: no such table: customUser</code>. </p>
<p>I was able to solve this through running the command <code>python manage.py migrate --run-syncdb</code> . The command syncs tables by looking into tables not created and then creating them.</p>
<p>I also had an issue of using a port that was already being used by a program I had left running and forgotten about. </p>
<p>To close a port you should identify the process using it by running the command <code>lsof -i :&lt;port_number&gt;</code>. This will show you the user using it and PID. To stop the process use <code>kill &lt;PID&gt;</code>. Additionally, you can use <code>sudo kill -9 -u &lt;username&gt; &lt;pid&gt;</code> .</p>
<p>It's good to know that to kill the port you will need administrator permissions. Also, stopping a process can cause data loss or unusual behavior so ensure your data is backed up before doing this.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this tutorial, you have learned how JWTs work, the structure of different tokens, how to use JWT and DRF to get tokens, how to create and serve static files in Django, and how to handle deleting migration files and kill a port.</p>
<p>There is so much you can learn about <a target="_blank" href="https://www.djangoproject.com/">Django</a> and the <a target="_blank" href="https://www.django-rest-framework.org/">Django Rest Framework.</a></p>
<p>The code for this article can be found <a target="_blank" href="https://github.com/VeldaKiara/tokenization">here</a>.</p>
<p>May your keyboard be swift, your bugs be few, and your fun meter be off the charts as you code away!</p>
<p>Thanks for reading my article on how to implement tokenization using JWT and Django Rest Framework. I'm always up for a good chat about coding and tech, so give me a follow on <a target="_blank" href="https://twitter.com/VeldaKiara">Twitter</a> and let's continue the conversation there.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Set Up Java Spring Boot JWT Authorization and Authentication ]]>
                </title>
                <description>
                    <![CDATA[ By Yiğit Kemal Erinç In the past month, I had a chance to implement JWT auth for a side project. I have previously worked with JWT in Ruby on Rails, but this was my first time in Spring.  In this post, I will try to explain what I have ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-setup-jwt-authorization-and-authentication-in-spring/</link>
                <guid isPermaLink="false">66d45e44182810487e0ce155</guid>
                
                    <category>
                        <![CDATA[ authentication ]]>
                    </category>
                
                    <category>
                        <![CDATA[ authorization ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JSON Web Tokens ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JWT ]]>
                    </category>
                
                    <category>
                        <![CDATA[ spring-boot ]]>
                    </category>
                
                    <category>
                        <![CDATA[ spring security ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 12 Aug 2020 20:00:00 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/08/jwt.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Yiğit Kemal Erinç</p>
<p>In the past month, I had a chance to implement JWT auth for a side project. I have previously worked with JWT in Ruby on Rails, but this was my first time in Spring. </p>
<p>In this post, I will try to explain what I have learned and applied in my project to share my experience and hopefully help some people. </p>
<p>We will start by taking a quick look at the theory behind JWT and how it works. Then we will look at how to implement it in a Spring Boot application.</p>
<h2 id="heading-jwt-basics">JWT Basics</h2>
<p>JWT, or JSON Web Tokens (<a target="_blank" href="https://tools.ietf.org/html/rfc7519">RFC 7519</a>), is a standard that is mostly used for securing REST APIs. Despite being a relatively new technology, it is gaining rapid popularity.</p>
<p>In the JWT auth process, the front end (client) firstly sends some credentials to authenticate itself (username and password in our case, since we're working on a web application). </p>
<p>The server (the Spring app in our case) then checks those credentials, and if they are valid, it generates a JWT and returns it. </p>
<p>After this step client has to provide this token in the request’s <strong>Authorization</strong> header in the “Bearer TOKEN” form. The back end will check the validity of this token and authorize or reject requests. The token may also store user roles and authorize the requests based on the given authorities.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/1.jpg" alt="Image" width="600" height="400" loading="lazy"></p>
<h2 id="heading-implementation">Implementation</h2>
<p>Now let’s see how we can implement the JWT login and save mechanism in a real Spring application.</p>
<h3 id="heading-dependencies">Dependencies</h3>
<p>You can see the list of Maven dependencies that our example code uses below. Note that the core dependencies like Spring Boot and Hibernate are not included in this screenshot.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/2-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<h3 id="heading-saving-users">Saving Users</h3>
<p>We will start by creating controllers to save users securely and authenticate them based on username and password.</p>
<p>We have a model entity called User. It is a simple entity class that maps to the <strong>USER</strong> table. You can use whatever properties you need depending on your application.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/3-1.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We also have a simple <strong>UserRepository</strong> class to save users. We need to override the <strong>findByUsername</strong> method since we will use it in authentication.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">UserRepository</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">JpaRepository</span>&lt;<span class="hljs-title">User</span>, <span class="hljs-title">String</span>&gt;</span>{ 
    <span class="hljs-function">User <span class="hljs-title">findByUsername</span><span class="hljs-params">(String username)</span></span>; 
}
</code></pre>
<p>We should never store plaintext passwords in the database because many users tend to use the same password for multiple sites. </p>
<p>There are many different hashing algorithms, but the most commonly used one is <strong>BCrypt</strong> and it is a recommended method of secure hashing. You can check out <a target="_blank" href="https://security.blogoverflow.com/2013/09/about-secure-password-hashing/#:~:text=Passwords%20should%20be%20hashed%20with,providing%20most%20security%20is%20bcrypt.">this</a> article for more information on the topic.</p>
<p>To hash the password, we will define a <strong>BCrypt</strong> bean in <strong>@SpringBootApplication</strong> and annotate the main class as follows:</p>
<pre><code class="lang-java"><span class="hljs-meta">@Bean</span> <span class="hljs-function"><span class="hljs-keyword">public</span> BCryptPasswordEncoder <span class="hljs-title">bCryptPasswordEncoder</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> BCryptPasswordEncoder(); 
}
</code></pre>
<p>We will call the methods on this bean when we need to hash a password.</p>
<p>We also need a UserController to save users. We create the controller, annotate it with <strong>@RestController,</strong> and define the corresponding mapping. </p>
<p>In our application, we save the user based on a DTO object that is passed from the front end. You can also pass a User object in <strong>@RequestBody</strong>.</p>
<p>After we pass the DTO object, we encrypt the password field using the <strong>BCrypt</strong> bean we created earlier. You could also do this in the controller, but it is a better practice to put this logic in the service class.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Transactional(rollbackFor = Exception.class)</span> 
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">saveDto</span><span class="hljs-params">(UserDto userDto)</span> </span>{ 
    userDto.setPassword(bCryptPasswordEncoder
           .encode(userDto.getPassword())); 
    <span class="hljs-keyword">return</span> save(<span class="hljs-keyword">new</span> User(userDto)).getId(); 
}
</code></pre>
<h3 id="heading-authentication-filter">Authentication Filter</h3>
<p>We need authentication to make sure that the user is really who they claim to be. We will be using the classic username/password pair to accomplish this.</p>
<p>Here are the steps to implement authentication:</p>
<ol>
<li>Create our Authentication Filter that extends <strong>UsernamePasswordAuthenticationFilter</strong></li>
<li>Create a security configuration class that extends <strong>WebSecurityConfigurerAdapter</strong> and apply the filter</li>
</ol>
<p>Here is the code for our Authentication Filter – as you might know, filters are the backbone of Spring Security.</p>


<p>Let’s go over this code step by step.</p>
<p>This class extends <strong>UsernamePasswordAuthenticationFilter</strong> which is the default class for password authentication in Spring Security. We extend it to define our custom authentication logic.</p>
<p>We make a call to the <strong>setFilterProcessesUrl</strong> method in our constructor. This method sets the default login URL to the provided parameter. </p>
<p>If you remove this line, Spring Security creates the <strong>“/login”</strong> endpoint by default. It defines the login endpoint for us, which is why we will not define a login endpoint in our controller explicitly. </p>
<p>After this line our login endpoint will be <strong>/api/services/controller/user/login</strong>. You can use this function to stay consistent with your endpoints.</p>
<p>We override the <strong>attemptAuthentication</strong> and <strong>successfulAuthentication</strong> methods of the <strong>UsernameAuthenticationFilter</strong> class.</p>
<p>The <strong>attemptAuthentication</strong> function runs when the user tries to log in to our application. It reads the credentials, creates a user POJO from them, and then checks the credentials to authenticate. </p>
<p>We pass the username, password, and an empty list. The empty list represents the authorities (roles), and we leave it as is since we do not have any roles in our application yet.</p>
<p>If the authentication is successful, the <strong>successfulAuthentication</strong> method runs. The parameters of this method are passed by Spring Security behind the scenes. </p>
<p>The <strong>attemptAuthentication</strong> method returns an <strong>Authentication</strong> object that contains the authorities we passed while attempting. </p>
<p>We want to return a token to user after authentication is successful, so we create the token using username, secret, and expiration date. We need to define the <strong>SECRET</strong> and <strong>EXPIRATION_DATE</strong> now.</p>


<p>We create a class to be a container for our constants. You can set the secret to whatever you want, but the best practice is making the secret key as long as your hash. We use the <strong>HS256</strong> algorithm in this example, so our secret key is 256 bits/32 chars.</p>
<p>The expiration time is set to 15 minutes, because it is the best practice against secret key brute-forcing attacks. The time is in milliseconds.</p>
<p>We have prepared our Authentication filter, but it is not active yet. We also need an Authorization filter, and then we will apply them both through a configuration class. </p>
<p>This filter will check the existence and validity of the access token on the Authorization header. We will specify which endpoints will be subject to this filter in our configuration class.</p>
<h3 id="heading-authorization-filter">Authorization Filter</h3>


<p>The <strong>doFilterInternal</strong> method intercepts the requests then checks the Authorization header. If the header is not present or doesn’t start with “BEARER”, it proceeds to the filter chain. </p>
<p>If the header is present, the <strong>getAuthentication</strong> method is invoked. <strong>getAuthentication</strong> verifies the JWT, and if the token is valid, it returns an access token which Spring will use internally. </p>
<p>This new token is then saved to SecurityContext. You can also pass in Authorities to this token if you need for role-based authorization.</p>
<p>Our filters are ready, and now we need to put them into action with the help of a configuration class.</p>
<h3 id="heading-configuration">Configuration</h3>


<p>We annotate this class with <strong>@EnableWebSecurity</strong> and extend <strong>WebSecurityConfigureAdapter</strong> to implement our custom security logic. </p>
<p>We autowire the BCrypt bean that we defined earlier. We also autowire the <strong>UserDetailsService</strong> to find the user’s account. </p>
<p>The most important method is the one which accepts an <strong>HttpSecurity</strong> object. Here we specify the secure endpoints and filters that we want to apply. We configure CORS, and then we permit all post requests to our sign up URL that we defined in the constants class. </p>
<p>You can add other ant matchers to filter based on URL patterns and roles, and you can <a target="_blank" href="https://stackoverflow.com/questions/44067650/spring-security-role-based-access">check</a> this StackOverflow question for examples regarding that. The other method configures the <strong>AuthenticationManager</strong> to use our encoder object as its password encoder while checking the credentials.</p>
<h3 id="heading-testing">Testing</h3>
<p>Let’s send a few requests to test if it works properly.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/4.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Here we send a GET request to access a protected resource. Our server responds with a 403 code. This is the expected behavior because we haven’t provided a token in the header. Now let’s create a user:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/5.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>To create a user, we send a post request with our User DTO data. We will use this user to login and get an access token.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/6.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Great! We got the token. After this point, we will use this token to access protected resources.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/08/7.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>We provide the token in the Authorization header and we are now allowed access to our protected endpoint.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial I have walked you through the steps I took when implementing JWT authorization and password authentication in Spring. We also learned how to save a user securely. </p>
<p>Thank you for reading – I hope it was helpful to you. If you are interested in reading more content like this, feel free to subscribe to my blog at <a target="_blank" href="https://erinc.io">https://erinc.io</a>. :)</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ What are JSON Web Tokens? JWT Auth Tutorial ]]>
                </title>
                <description>
                    <![CDATA[ Most web apps use security measures to make sure user data stays private. Authentication is a key part of security and JSON Web Tokens (JWT) are a great way to implement authentication. So what are JSON Web Tokens? JWT is a standard that defines a co... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-are-json-web-tokens-jwt-auth-tutorial/</link>
                <guid isPermaLink="false">66b20710903dc07a135166ab</guid>
                
                    <category>
                        <![CDATA[ JSON Web Tokens ]]>
                    </category>
                
                    <category>
                        <![CDATA[ youtube ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Beau Carnes ]]>
                </dc:creator>
                <pubDate>Tue, 12 Nov 2019 20:51:31 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/11/jwt.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Most web apps use security measures to make sure user data stays private. Authentication is a key part of security and JSON Web Tokens (JWT) are a great way to implement authentication.</p>
<h2 id="heading-so-what-are-json-web-tokens">So what are JSON Web Tokens?</h2>
<p>JWT is a standard that defines a compact and self-contained way to securely transmit information between a client and a server as a JSON object. The compact size makes the tokens easy to transfer through an URL, POST parameter, or inside an HTTP header. Also, since they are self-contained they include all the necessary information about a user so the database does not need to be queried more than once.</p>
<p>The information in a JWT can be trusted because it is digitally signed using a secret or public/private key pair.</p>
<h2 id="heading-authentication">Authentication</h2>
<p>JWT are mainly used for authentication. After a user logs in to an application, the application will create a JWT and send it back to the user. Subsequent requests by the user will include the JWT. The token tells the server what routes, services, and resources the user is allowed to access. JWT can be easily used across multiple domains so they are often used for Single Sign On.</p>
<h2 id="heading-using-json-web-tokens">Using JSON Web Tokens</h2>
<p>Thomas Weibenfalk made an excellent video tutorial that explains JSON Web Tokens and demonstrates how to use them for authentication. The tutorial teaches JWT Auth as simply as possible, without using a lot of extra libraries.</p>
<p>Watch the tutorial below or on <a target="_blank" href="https://www.youtube.com/watch?v=x5gLL8-M9Fo">the freeCodeCamp.org YouTube channel</a> (2 hour watch).</p>
<div class="embed-wrapper">
        <iframe width="560" height="315" src="https://www.youtube.com/embed/x5gLL8-M9Fo" style="aspect-ratio: 16 / 9; width: 100%; height: auto;" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen="" loading="lazy"></iframe></div>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
