<?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" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Acharouaou-mohamed on Medium]]></title>
        <description><![CDATA[Stories by Acharouaou-mohamed on Medium]]></description>
        <link>https://medium.com/@acharouaoumohamed?source=rss-a7501fc0b13c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3MXGvxzdKn7lI_uz8sHqkw.jpeg</url>
            <title>Stories by Acharouaou-mohamed on Medium</title>
            <link>https://medium.com/@acharouaoumohamed?source=rss-a7501fc0b13c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:10:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@acharouaoumohamed/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[JWT vs OAuth 2: Understanding Authentication and Authorization with Examples]]></title>
            <link>https://medium.com/@acharouaoumohamed/jwt-vs-oauth-2-understanding-authentication-and-authorization-with-examples-9ab73b2d2399?source=rss-a7501fc0b13c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ab73b2d2399</guid>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[oauth2-provider]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[token]]></category>
            <dc:creator><![CDATA[Acharouaou-mohamed]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 21:55:57 GMT</pubDate>
            <atom:updated>2024-12-10T22:01:09.627Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FjQd2-YHP6xl1HleVpo0yA.jpeg" /></figure><p>In the world of secure web applications, authentication and authorization are two key pillars. While JSON Web Tokens (JWT) and OAuth 2 are both crucial in this space, they serve different purposes. If you’ve ever wondered how they work together or how they differ, this article breaks it down step by step — with code examples and illustrations.</p><h3>What is JWT?</h3><p>Think of <strong>JWT</strong> as a secure badge you give to users to prove their identity and permissions. It’s a compact, self-contained token containing:</p><ul><li>The user’s identity.</li><li>Their roles or permissions.</li><li>Token expiration time.</li></ul><p>A JWT looks something like this:</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyMSIsInJvbGUiOiJVU0VSIiwiZXhwIjoxNjkwMDY3MjAwfQ.-P8HHaIcGrYN9S5H8QBtBtd0H4N0z6gXeQ1g8VVLPX8</pre><p>It’s split into three parts:</p><ol><li><strong>Header</strong>: Contains metadata like the algorithm used to sign the token.</li><li><strong>Payload</strong>: Contains user data and claims.</li><li><strong>Signature</strong>: Verifies the token’s authenticity.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AdkohjoRSTfCwbLh-ir7ug.png" /><figcaption><em>A visual breakdown of the JWT structure (Header, Payload, Signature).</em></figcaption></figure><h3>How JWT Works (Without OAuth 2)</h3><p>Imagine you’re building a secure digital library. Users log in with their credentials, and your application:</p><ol><li>Verifies their username and password.</li><li>Issues a JWT containing their role (e.g., USER, ADMIN).</li><li>Sends the JWT back to the user.</li></ol><p>Every time the user accesses a protected resource, they include the JWT in their request. Your app validates the token and grants or denies access.</p><h3>What is OAuth 2?</h3><p><strong>OAuth 2</strong> is a <em>framework</em> for secure, scalable authentication and authorization. Instead of handling login and role management yourself, you delegate these tasks to a trusted <strong>identity provider</strong> like <strong>Okta</strong> or <strong>Keycloak</strong>. OAuth 2 defines the process for:</p><ul><li>Users logging in.</li><li>Applications obtaining access tokens (like JWTs) on behalf of users.</li><li>Validating these tokens to ensure they’re legitimate.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pHXgV4UrpUgWAnv1v7ZvsQ.png" /><figcaption><em>A diagram showing the interaction between a user, your app, and an identity provider during the OAuth 2 flow.</em></figcaption></figure><h3>How JWT Fits into OAuth 2</h3><p>In OAuth 2, JWT often serves as the token issued by the identity provider. It’s how the provider communicates the user’s identity and permissions to your application.</p><p>Key benefits:</p><ul><li><strong>Centralized Authentication</strong>: All users authenticate via the identity provider.</li><li><strong>Scalability</strong>: Multiple services can trust the same identity provider.</li><li><strong>Simpler Token Validation</strong>: Your app doesn’t need to manage keys or user databases.</li></ul><h3>Step-by-Step Comparison: JWT Without OAuth vs With OAuth</h3><p><strong>Without OAuth 2With OAuth 2</strong>App generates and validates JWT manually.Identity provider generates and validates JWT.App manages user authentication and roles.Identity provider handles authentication and roles.Suitable for simple or internal apps.Ideal for complex, multi-service ecosystems.</p><h3>Code Examples</h3><h3>1. JWT Without OAuth 2</h3><p>Here, your application handles login, token generation, and validation.</p><h4>Login Endpoint</h4><pre>@RestController<br>@RequestMapping(&quot;/auth&quot;)<br>public class AuthController {<br>private final String SECRET_KEY = &quot;my-secret-key&quot;;<br>    @PostMapping(&quot;/login&quot;)<br>    public ResponseEntity&lt;?&gt; login(@RequestBody AuthRequest authRequest) {<br>        if (&quot;user&quot;.equals(authRequest.getUsername()) &amp;&amp; &quot;password&quot;.equals(authRequest.getPassword())) {<br>            String token = Jwts.builder()<br>                    .setSubject(authRequest.getUsername())<br>                    .claim(&quot;role&quot;, &quot;USER&quot;)<br>                    .setIssuedAt(new Date())<br>                    .setExpiration(new Date(System.currentTimeMillis() + 3600000))<br>                    .signWith(SignatureAlgorithm.HS256, SECRET_KEY.getBytes())<br>                    .compact();<br>            return ResponseEntity.ok(new AuthResponse(token));<br>        }<br>        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(&quot;Invalid credentials&quot;);<br>    }<br>}</pre><h3>2. JWT with OAuth 2</h3><p>When using OAuth 2, an identity provider like Okta or Keycloak manages login, token generation, and validation.</p><h4>Setup</h4><p>In your application.yml:</p><pre>spring:<br>  security:<br>    oauth2:<br>      resourceserver:<br>        jwt:<br>          issuer-uri: https://your-identity-provider/.well-known/openid-configuration</pre><h4>Protecting Endpoints</h4><pre>@RestController<br>@RequestMapping(&quot;/protected&quot;)<br>public class ProtectedController {<br>@GetMapping(&quot;/user&quot;)<br>    @PreAuthorize(&quot;hasAuthority(&#39;ROLE_USER&#39;)&quot;)<br>    public ResponseEntity&lt;String&gt; userAccess() {<br>        return ResponseEntity.ok(&quot;Welcome, USER!&quot;);<br>    }<br>    @GetMapping(&quot;/admin&quot;)<br>    @PreAuthorize(&quot;hasAuthority(&#39;ROLE_ADMIN&#39;)&quot;)<br>    public ResponseEntity&lt;String&gt; adminAccess() {<br>        return ResponseEntity.ok(&quot;Welcome, ADMIN!&quot;);<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IjDqRAXzfaPTZYCSoLOj7Q.png" /><figcaption><em>A flow diagram showing the OAuth 2 login process (user → identity provider → app).</em></figcaption></figure><h3>Which One Should You Use?</h3><ul><li>Use <strong>JWT without OAuth 2</strong> for simple apps where you manage users and roles internally.</li><li>Use <strong>JWT with OAuth 2</strong> when:</li><li>You have multiple apps or services.</li><li>You want a centralized, secure way to handle authentication and authorization.</li></ul><h3>Conclusion</h3><p>JWT and OAuth 2 work beautifully together. JWT provides a compact, secure way to communicate user data, while OAuth 2 offers a standardized, scalable way to handle authentication and authorization across systems. Depending on your application’s complexity, choose the approach that fits your needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q1ENcd85C01N33Kq6kGM1w.png" /><figcaption><em>A closing graphic summarizing the JWT and OAuth 2 relationship.</em></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ab73b2d2399" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>