<?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 İbrahim Erdoğan on Medium]]></title>
        <description><![CDATA[Stories by İbrahim Erdoğan on Medium]]></description>
        <link>https://medium.com/@ibrahimerdogandev?source=rss-3936637a32ae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0mKDzZnBvyRdlWOUkBGUMg.jpeg</url>
            <title>Stories by İbrahim Erdoğan on Medium</title>
            <link>https://medium.com/@ibrahimerdogandev?source=rss-3936637a32ae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 14:53:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ibrahimerdogandev/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[OAuth 2.0: Temel Kavramlar, Terminoloji ve Yetkilendirme Akışları]]></title>
            <link>https://medium.com/@ibrahimerdogandev/oauth-2-0-temel-kavramlar-terminoloji-ve-yetkilendirme-ak%C4%B1%C5%9Flar%C4%B1-81c3cf6467a3?source=rss-3936637a32ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/81c3cf6467a3</guid>
            <dc:creator><![CDATA[İbrahim Erdoğan]]></dc:creator>
            <pubDate>Thu, 15 Jan 2026 00:00:29 GMT</pubDate>
            <atom:updated>2026-03-17T20:17:58.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*_075nr9pwJOxOHWrJjR28A.png" /></figure><p>Modern web uygulamalarında, farklı servislerin,sistemlerin birbirleriyle güvenli bir şekilde iletişim kurması kritik bir öneme sahiptir. Bir hizmeti kullanırken , ilgili sistemde oturum açtıktan sonra, başka bir sistemdeki verilere de erişim sağlamamız gereken durumlar olabilir. Online fotoğraf baskı hizmeti sunan bir firmamızın olduğunu düşünelim, müşterilerimiz sistemimize girdikten sonra , fotoğraflarını seçmek için Google Drive’daki fotoğraflarına erişmek isteyebilir. Bunun gibi senaryolarda OAuth 2.0 protokolü yardımcı bir protokol olarak karşımıza çıkmaktadır.</p><p>OAuth 2.0, servisler arası yetkilendirme (authorization) için tasarlanmış bir standarttır. Makalemizde, OAuth 2.0&#39;ın temel kavramlarını ve önemli yetkilendirme akışlarını detaylı bir şekilde inceleyeceğiz.</p><h3>OAuth 2.0 Nedir?</h3><p>OAuth ismindeki “Auth” kelimesi çoğu zaman authentication (kimlik doğrulama) ile karıştırılır, ancak buradaki “auth” authorization (yetkilendirme) anlamına gelir. OAuth 2.0, bir servisin başka bir servise erişim yetkisi vermesi için tasarlanmıştır — bir kullanıcının, kimliğini doğrulamak için <strong>kullanılmamaktadır</strong>.</p><p>OAuth başlangıçta bir servisin bir kişiyi yetkilendirmesi için değil, bir servisin başka bir servisi yetkilendirmesi için oluşturulmuştur. Peki neden bir servis başka bir servisi yetkilendirsin? Bu sorunun cevabını klasik bir örnekle açıklayalım.</p><h3>Fotoğraf Baskı sistemi analojisi üzerinden OAuth</h3><p>Bir fotoğraf baskı hizmeti sunan web sitesi düşünelim.<br>Kullanıcılar sisteme fotoğraf yükleyerek baskı siparişi verebiliyor. Ancak her kullanıcının fotoğraflarını tek tek bilgisayarından yüklemesi hem <strong>kullanıcı deneyimini zorlaştırıyor</strong>, hem <strong>altyapı maliyetini artırıyor</strong>, hem de <strong>güvenlik riskleri</strong> doğuruyor.</p><p>Günümüzde kullanıcıların büyük bir kısmı fotoğraflarını artık yerel bilgisayarlarda değil, <strong>Google Drive gibi bulut servislerinde</strong> saklıyor. Bu noktada kullanıcı şu soruyu soruyor:</p><p><strong>“Google Drive’daki fotoğraflarımı doğrudan içe aktarabilir miyim?”</strong></p><p>Böyle bir özellik kullanıcı için büyük bir kolaylık sağlar. Ancak burada da kritik bir problem vardır:</p><p>Google Drive’daki dosyalar Google tarafından korunmaktadır ve bu dosyalara erişim için Google kimlik doğrulaması gereklidir.</p><p>Peki web sitemiz, kullanıcının Google kullanıcı adı ve şifresini istemeden, kullanıcı adına Google Drive’daki fotoğraflara nasıl erişebilir?</p><h3>Yanlış Yaklaşım: Kullanıcı Kimlik Bilgilerini İstemek</h3><p>Teoride: kullanıcıdan Google ID ve şifresini isteyerek bu süreci gerçekleştirebileceğimizi düşünebiliriz.Fakat kullanıcıların bu secret bilgileri paylaşmayacağını düşündüğümüzde , bu fikrin teorinin ötesine geçemeyeceğini rahatlıkla söyleyebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LqJzwBNQk-cTmQJP.png" /></figure><h3>Vale — Anahtar Analojisi</h3><p>OAuth’u anlamak için çok yaygın kullanılan bir analoji vardır: vale — anahtar modeli. Bir araç sahibi otoparka gelir, arabadan iner ve anahtarı vale’ye verir, aracını park etmesini rica eder. Vale anahtarı alır, arabayı park yerine çeker ve park eder.</p><p>Ancak bazı araç sahiplerinin vale’ye anahtar teslimi yaparken endişesi olabilir. :) Arabanın bagajina koyduğu veya torpidosuna koyduğu kıymetli bir eşyasının gidebileceğini düşünebilir veya aracının başka bir yere götürülebileceğini…</p><p>Bazı arabalar, bu tarz durumlarda kullanmak üzere, ek bir anahtar ile gelir: valet anahtar. Valet anahtar, ana araba anahtarı gibidir ama sınırlı erişime sahiptir:</p><p>* Arabayı çalıştırabilir ve durdurabilir</p><p>* Bagajı veya torpido gözünü açamaz</p><p>* Yakıt deposunu açamaz</p><p>Araç sahibi böyle bir anahtara sahipse, vale’ye vermek konusunda daha rahat olur , vale’nin bu anahtarla amaçlanan işinin dışında bir şey yapamayacağını bilir.</p><p>OAuth bu şekilde çalışır: ilgili sisteme -tam kimlik bilgileri yerine ,sınırlı erişim sağlayan- bir ‘valet anahtar’ (access token) verilir.</p><h3>OAuth 2.0 Nasıl Çalışır?</h3><p>Fotoğraf baskı hizmeti sunan web uygulamasında, kullanıcıların Google Drive hesaplarındaki görsellere doğrudan erişebilmek önemli bir kullanım kolaylığı sağlar. Ancak bu senaryoda bir güven problemi ortaya çıkar:</p><p>Kullanıcı hem fotoğraf baskı servisine hem de Google hesabına giriş yapmış olsa da, bu iki sistem <strong>birbirlerine doğrudan güvenmez</strong>. Her sistem yalnızca kullanıcıyı tanır ve doğrular; üçüncü taraf bir servisin, kullanıcı adına işlem yapabilmesi için ek bir yetkilendirme mekanizmasına ihtiyaç vardır.</p><p>Bu noktada, fotoğraf baskı servisinin Google’a doğrudan “kullanıcının dosyalarına erişmek istiyorum” talebinde bulunması yeterli değildir. Google açısından bu talep, kimliği ve yetkisi doğrulanmamış bir üçüncü taraf isteği olarak değerlendirilir ve reddedilir. Google, kullanıcı verilerine erişim konusunda yalnızca <strong>kullanıcının açık onayına dayalı</strong> işlemleri kabul eder.</p><p>OAuth protokolü bu güven problemini çözmek üzere tasarlanmıştır. OAuth kullanan bir sistemde, üçüncü taraf servisler (bu örnekte fotoğraf baskı servisi) kullanıcı adına doğrudan veri talep etmek yerine, yetkilendirme sürecini kullanıcının kendisine yönlendirir.</p><p>Bu akışta şu adımlar gerçekleşir:</p><p>1-Fotoğraf baskı servisi, Google’a kullanıcının dosyalarına erişmek istediğini bildirir.</p><p>2-Google, bu talebi doğrudan kabul etmek yerine kullanıcıyı bir yetkilendirme ekranına yönlendirir.</p><p>Bu ekranda kullanıcıya:</p><ul><li>Hangi servisin erişim talep ettiği,</li><li>Hangi tür izinlerin istendiği (örneğin yalnızca dosya okuma),</li><li>Bu erişimin hangi amaçla kullanılacağı<br>açık bir şekilde sunulur.</li></ul><p>3-Kullanıcı, talebi onayladığı takdirde Google bu servise <strong>erişim belirteci (access token)</strong> üretir.</p><p>Bu access token, OAuth bağlamında sınırlı yetkilere sahip bir kimlik bilgisi olarak değerlendirilir. Tam kullanıcı kimlik bilgileri paylaşılmaz; bunun yerine yalnızca kullanıcının onayladığı kapsam (scope) dahilinde işlem yapabilen geçici bir yetki verilir. Bu yapı, valet anahtar analojisinde olduğu gibi, erişimi yalnızca gerekli işlevlerle sınırlar.</p><p>Bundan sonraki adımlarda fotoğraf baskı servisi, Google Drive API’sine yaptığı her istekte bu access token’ı kullanır. Google, gelen istekteki token’ı doğrular; token geçerli ve yetki kapsamı uygun ise ilgili kaynağa erişime izin verir. Aksi durumda erişim reddedilir.</p><p>Bu yaklaşım sayesinde:</p><ul><li>Kullanıcı parolaları üçüncü taraf servislerle paylaşılmaz,</li><li>Erişim kapsamı net bir şekilde sınırlandırılır,</li><li>Kullanıcı, verileri üzerindeki kontrolü tamamen elinde tutar.</li></ul><h3>OAuth 2.0 Terminolojisi</h3><p>OAuth uygulamalarında, makalelerde ve dokümantasyonlarda karşılaşacağınız temel terminolojiyi analojimiz üzerinden anlatmaya devam edelim;</p><p>1. Resource (Kaynak)</p><p>Resource, OAuth akışındaki tüm aktörlerin erişmeye çalıştığı şeydir. Korunan kaynak (protected resource) olarak da adlandırılır.Örneğimizde kaynak nedir? Google Drive’daki fotoğraflar. OAuth akışının tüm amacı bu kaynağa erişim sağlamaktır.</p><p>2. Resource Owner (Kaynak Sahibi)</p><p>Resource Owner, kaynağa şu anda erişimi olan kişidir — yani kullanıcı. OAuth spesifikasyonundaki tanımı: “Korunan kaynağa erişim izni verebilen varlıktır.” Fotoğraf baskı servisi örneğini düşünürsek, kaynağa erişime ihtiyaç duyuyor, bu örnekte erişimi -Kaynak sahibi, yani fotoğrafları Google Drive’da olan kişi- verebilir.</p><p>3. Resource Server (Kaynak Sunucusu)</p><p>Resource Server, korunan kaynağı barındıran sunucudur. Örneğimizde Google Drive kaynak sunucusudur.Kaynak sunucusu korunan kaynağı barındırıp ve yönetir.</p><p>4. Client (İstemci)</p><p>Client, korunan kaynağa erişmesi gereken uygulamadır. Kaynak sahibi adına ve kaynak sahibinin yetkilendirmesiyle korunan kaynağa istekte bulunan uygulamadır.</p><p>Örneğimizde:</p><p>* Kullanıcı (laptop başındaki kişi) = Resource Owner</p><p>* Google Drive = Resource Server</p><p>* Fotoğraf baskı servisi = Client</p><p>5. Authorization Server (Yetkilendirme Sunucusu)</p><p>Güvenlik sorumluluğu kaynak sunucunun üzerindedir. Kaynak sunucusu, kaynağın güvenliğini sağlamakla yükümlüdür.Bu nedenle kaynak sunucusu genellikle bir Authorization Server ile birlikte gelir. Yetkilendirme sunucusu, kaynağa erişen herkesin yetkili olduğundan emin olmaktan sorumludur. Authorization Server, client’a access token’lar veren sunucudur.</p><p>Bilgi: Resource Server ve Authorization Server aynı sunucu olabilir veya ayrı sunucular olabilir. Spesifikasyon bu konuda detaylı bilgi vermez, ancak kavramsal olarak iki ayrı sorumluluk alanı olarak düşünülebilir.</p><h3>OAuth 2.0 Akışları (Flows)</h3><p>OAuth için kurgulanmış olan akışlar ve uygulamalar mevcuttur. Bu bölümde bilmeniz gereken üç önemli akışı inceleyeceğiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/0*cey5-J_dVZuuxDBf.png" /></figure><p><strong>1. Authorization Code Flow (Yetkilendirme Kodu Akışı)</strong></p><p>En güvenli ve en çok önerilen OAuth akışıdır. Kaynak sahibi, client ve authorization server arasında gerçekleşir.</p><ul><li>Kullanıcı, client uygulamasında “Google hesabımla giriş yap” / “hesabıma erişim izni ver” gibi bir işlem başlatır.</li><li>Client, kullanıcıyı Authorization Server’a yönlendirir (genellikle tarayıcı üzerinden redirect).</li><li>Authorization Server, kullanıcıyı doğrular (login ekranı gösterir) ve hangi izinleri (scope) istediğini gösterir.</li><li>Kullanıcı izinleri onaylar (Consent ekranı).</li><li>Authorization Server, client’a authorization code (tek kullanımlık, kısa ömürlü kod) verir → bunu redirect_uri üzerinden client’a geri gönderir.</li><li>Client, bu authorization code’u alır ve Authorization Server’a arka planda (backend-to-backend) bir istek yapar:</li></ul><blockquote><strong><em>code + client_id + client_secret + redirect_uri</em></strong></blockquote><p>Authorization Server kodu doğrular ve client’a şu ikiliyi verir:</p><blockquote>access_token (kısa ömürlü, kaynak erişimi için kullanılır)</blockquote><blockquote><strong><em>refresh_token (isteğe bağlı, uzun ömürlü; access token yenilemek için)</em></strong></blockquote><ul><li>Client artık access_token’ı kullanarak Resource Server’a (örneğin Google API, Drive, Gmail vs.) istek yapar.</li><li>Resource Server token’ı doğrular ve istenen kaynağı (veri) döndürür.</li></ul><p>Neden en güvenli kabul edilir?</p><p>Authorization code , tarayıcıda açıkta dolaşmaz. Access token ve özellikle client_secret sadece backend’de kullanılır. Refresh token ile uzun süreli erişim güvenli şekilde yönetilebilir.</p><p><strong>2. Implicit Flow (Örtük Akış)</strong></p><p>Implicit Flow, Authorization Code Flow’a benzer ancak biraz daha basitleştirilmiştir.</p><p>Akış şu şekilde çalışır:</p><p>Adım 1–4: İlk dört adım Authorization Code Flow ile aynıdır. Kullanıcı istek yapar, client authorization server’a gider, authorization server kullanıcıdan onay alır.</p><p>Adım 5: Authorization server, authorization token verip client’ın bunu access token’a dönüştürmesini beklemek yerine, doğrudan access token gönderir.</p><p>Adım 6–7: Client bu access token ile doğrudan resource server’ı çağırır ve kaynağı alır.</p><p>Bu akışın bir dezavantajı vardır: Access token, kaynağa erişmek için gereken tek şeydir. Birisi access token’a erişirse, bu servis gibi davranıp kaynağa erişebilir.</p><p>Authorization Code Flow’da access token daha güvenli bir şekilde değiştirilebilir, bu nedenle daha güvenlidir.</p><p>Implicit Flow şu durumlarda kullanılır:</p><p>* JavaScript uygulamaları (tarayıcıda çalışan)</p><p>* Access token’ın zaten çok güvenli olmadığı durumlar (tarayıcıda saklanacak)</p><p>* Basit ve hızlı entegrasyon gereken durumlar</p><p>Bu akışta access token’lar kısa ömürlü olmalıdır.</p><p>Implicit Flow artık önerilmemektedir, Modern uygulamalarda PKCE ile Authorization Code Flow kullanılması tavsiye edilir.</p><p><strong>3. Client Credentials Flow (İstemci Kimlik Bilgileri Akışı)</strong></p><p>Bu akış, microservices için uygun bir kullanım akışıdır. Client’ın güvenilir olduğu durumlarda genellikle kullanılır.</p><p>Örnek:İki microservice’imiz olsun. Microservice 1, Microservice 2&#39;deki bir API’yi çağırmak istesin. Microservice 2&#39;nin veritabanına erişimi var. Microservice 1, Microservice 2&#39;yi çağırdığında sadece belirli API’lere erişebilmeli, diğer API’lere ve verilere erişememeli.</p><p>Client Credentials Flow şu şekilde çalışır:</p><p>Adım 1: Microservice 1, Microservice 2&#39;deki bir API’yi çağırmak ister.</p><p>Adım 2: Önce OAuth sunucusuna bir çağrı yapar ve özel bir client ID sağlar: (kendisini tanıtır)</p><p>Adım 3: OAuth mikroservisi doğrular, belirli kaynaklara erişim için gerekli olan access token’ı hazırlayıp verir.</p><p>Adım 4: Microservice 1 bu token’ı saklar.</p><p>Adım 5: Microservice 1, Microservice 2&#39;yi çağırır. Microservice 2 token’ı kontrol eder.</p><p>Adım 6: Eğer Microservice 1 , token’ın yetkisinin bulunmadığı bir kaynağa erişmeye çalışırsa, bu isteği reddedilir.</p><p>Client Credentials Flow, microservice mimarilerinde servisler arası yetkilendirme genellikle tercih edilir. Her microservice’in ihtiyaç duyduğu verilere erişmesini sağlar.</p><p><strong>4. PKCE Flow (Proof Key for Code Exchange)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hLJF8zBb40JxhGfW.png" /></figure><p>PKCE, Authorization Code Flow’un bir uzantısıdır. Özellikle mobil uygulamalar ve Single Page Applications (SPA) için tasarlanmıştır. Implicit Flow’un yerini almıştır.</p><p>PKCE’nin temel akışını aşağıdaki gibi özetleyebiliriz:</p><p>1. Client rastgele bir “code verifier” oluşturur</p><p>2. Bu verifier’ın hash’ini (code challenge) authorization server’a gönderir</p><p>3. Authorization code alındığında, orijinal verifier’ı da gönderir</p><p>4. Server, verifier’ın hash’inin önceki challenge ile eşleştiğini doğrular</p><p>Bu sayede authorization code ele geçirilse bile, code verifier olmadan access token alınamaz.</p><p>Access Token Formatı: JWT</p><p>Access token’larda , verilen izinler , eksiksiz bir şekilde barındırılmalıdır. Aynı zamanda doğrulanabilir olmalıdır. Günümüzde yaygın olarak kullanılan access token türü JWT(JSON Web Token) token’dir. JWT, OAuth 2.0&#39;da access token formatı olarak yaygın şekilde kullanılmaktadır.</p><p>JWT üç parçadan oluşur:</p><p>1. Header: Token tipini ve imzalama algoritmasını barındırır.</p><p>2. Payload: Kullanıcı bilgileri ve izinler’i içerir.</p><p>3. Signature: Token’ın değiştirilmediğini doğrulayan bir imza içerir.</p><p>Örnek bir JWT token yapısı:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c</p><h3>OAuth 2.0&#39;ın Avantajları</h3><ul><li>Delegated Access (Yetkilendirilmiş Erişim): Kullanıcı kimlik bilgilerini paylaşmadan servisler arası erişim sağlayabilir.</li><li>Açık Standart: İnternet üzerindeki tüm servisler birbirleriyle haberleşebilmek için aynı kurallar bütününü takip eder.</li><li>Sınırlı Erişim: “Valet” anahtar gibi, sadece belirli işlemler için izin verilebilir.</li><li>Güvenlik: Access token’lar kısa ömürlü olabilir ve gerektiğinde iptal edilebilir.</li><li>Kullanıcı Kontrolü: Kullanıcı hangi izinleri vereceğine kendisi karar verebilir.</li><li>Scope Bazlı İzinler: Farklı seviyede erişim izinleri tanımlanabilir.</li></ul><h3>Güvenlik Hususları</h3><p>OAuth 2.0 kullanırken dikkat edilmesi gereken güvenlik noktaları:</p><p>1. State Parameter: CSRF saldırılarına karşı koruma sağlar. Her authorization isteğinde benzersiz bir state değeri gönderilmeli ve callback’te doğrulanmalıdır</p><p>2. HTTPS Zorunluluğu: OAuth akışı mutlaka HTTPS üzerinden gerçekleşmelidir. HTTP üzerinden token’lar ele geçirilebilir</p><p>3. Token Saklama: Access token’lar güvenli şekilde saklanmalıdır. Tarayıcıda localStorage yerine httpOnly cookie tercih edilmelidir.</p><p>4. Token Ömrü: Access token’lar kısa ömürlü olmalı (1 saat gibi), refresh token’larla yenilenmelidir.</p><p>5. Scope Minimizasyonu: Sadece gereken izinler istenmelidir.</p><h3>Sonuç</h3><p>OAuth 2.0, modern web uygulamalarında servisler arası güvenli yetkilendirme için vazgeçilmez bir standarttır. Valet anahtar analojisinde olduğu gibi, tam kimlik bilgileri paylaşmak yerine sınırlı erişim sağlayan token’lar kullanır.</p><p>* Resource: Erişilmek istenen kaynak</p><p>* Resource Owner: Kaynağın sahibi (kullanıcı)</p><p>* Resource Server: Kaynağı barındıran sunucu</p><p>* Client: Kaynağa erişmek isteyen uygulama</p><p>* Authorization Server: Token’ları veren sunucu</p><p>Dört önemli akışı inceledik:</p><p>1. Authorization Code Flow: En güvenli, önerilen akış</p><p>2. Implicit Flow: Eski yöntem, artık önerilmiyor</p><p>3. Client Credentials Flow: Microservices için ideal akış</p><p>4. PKCE Flow: Mobil ve SPA uygulamaları için güvenli akış</p><p><strong>Zaman ayırıp bu yazıyı okuduğunuz için teşekkür ederim. </strong><br>İçeriğin faydalı olmasını dilerim.</p><p>Kaynaklar : <br><strong>What is OAuth really all about — OAuth tutorial — Java Brains -&gt; </strong><a href="https://www.youtube.com/watch?v=t4-416mg6iU">https://www.youtube.com/watch?v=t4-416mg6iU</a></p><p><strong>OAuth terminologies and flows explained — OAuth tutorial — Java Brains-&gt; </strong><a href="https://www.youtube.com/watch?v=3pZ3Nh8tgTE">https://www.youtube.com/watch?v=3pZ3Nh8tgTE</a></p><p><em>Originally published at </em><a href="https://celsushub.com/tr/blog/oauth-20-temel-kavramlar-terminoloji-ve-yetkilendirme-ak%C4%B1%C5%9Flar%C4%B1-7445"><em>https://celsushub.com</em></a><em> on January 15, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81c3cf6467a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT-Based Authentication and Authorization with Spring Security: A Step-by-Step Implementation]]></title>
            <link>https://medium.com/@ibrahimerdogandev/jwt-based-authentication-and-authorization-with-spring-security-a-step-by-step-implementation-4ef395683b28?source=rss-3936637a32ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ef395683b28</guid>
            <category><![CDATA[spring-boot-security]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[web-application-security]]></category>
            <category><![CDATA[spring-security]]></category>
            <dc:creator><![CDATA[İbrahim Erdoğan]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 07:07:16 GMT</pubDate>
            <atom:updated>2025-01-28T08:19:43.462Z</atom:updated>
            <content:encoded><![CDATA[<p>The exponential growth of data and information has brought about the critical need to ensure their protection. Studies have demonstrated that the volume of data and information generated in the digital age surpasses the total amount produced throughout human history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*EYKbL8aMQJLJKVO2UIVFOQ.jpeg" /><figcaption>Global Data Growth Trend Between 2006 and 2020</figcaption></figure><p><strong>The digital universe in 2020: big data, bigger digital shadows, and biggest growth in the far east</strong></p><p>With the evolution of the web, single-page websites have been replaced by dynamic web pages. As a result, access to information sources is now regulated through specific security frameworks. These frameworks protect information sources from unauthorized users or systems.</p><p>In this article, we will explore how to monitor and regulate access to our services and information sources using Spring Security, which is the de facto standard for security in Spring projects. We will also examine how to configure these monitoring mechanisms effectively. By employing these methods, we will safeguard the services we develop from unauthorized access.</p><p>Before we begin developing our application, let us consider some critical questions.</p><p><strong>What Are the Fundamental Security Requirements of a Website?</strong></p><p>Before diving into configurations, let’s examine what constitutes the security requirements of a website. The fundamental security needs of a website are composed of the following components:</p><ol><li><strong>Authentication</strong></li><li><strong>Authorization</strong></li><li><strong>Data Encryption</strong></li><li><strong>Logging</strong></li><li><strong>Firewall, IDS, and IPS Systems</strong></li><li><strong>DDoS Protection</strong></li><li><strong>Software Updates</strong></li><li><strong>Database Security</strong></li><li><strong>Error Management</strong></li><li><strong>Backup Solutions</strong></li><li><strong>Access Control Lists (ACLs)</strong></li><li><strong>Security Measures Against Attacks like XSS, CSRF, etc.</strong></li></ol><p>To address our security needs, we will proceed in this article by exploring how authentication and authorization processes are implemented using Spring Security.</p><p><strong>1- Authentication Processes in Spring Boot</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fi3d-6buKECWDGMVn3ynNQ.jpeg" /></figure><p>In general, the authentication lifecycle follows the steps outlined above. However, the specific components involved may vary depending on the scenario you are implementing.</p><p><strong>1 - HttpRequest</strong></p><p>The process begins when the user sends an HTTP request to access a protected resource in the application. This typically occurs through a login form (submitting a username and password) or an API request.</p><p><strong>2 - Authentication Filter</strong><br>The first checkpoint: The user’s request passes through an Authentication Filter. For example:<br>A <strong>UsernamePasswordAuthenticationFilter </strong>captures the username and password provided by the user.<br>In a token-based system, this filter validates a <strong>JWT (JSON Web Token)</strong> or another type of token.<br>It then creates a <strong>UsernamePasswordAuthenticationToken </strong>object containing the user’s login credentials.</p><p><strong>3 - Authentication Token</strong><br>At this stage, the authentication token (e.g., <strong>UsernamePasswordAuthenticationToken</strong>) created by the filter is passed to Spring Security’s Authentication Manager. This token contains information such as the username and password.</p><p><strong>4 - Authentication Manager</strong><br>The central dispatcher: This component selects the appropriate Authentication Provider to validate the authentication token.<br>For example, in an application that uses both DaoAuthenticationProvider and <strong>LdapAuthenticationProvider</strong>, the Authentication Manager determines which provider to use for the token.</p><p><strong>5 - Authentication Provider</strong><br>The authentication process is executed here: The chosen <strong>Authentication Provider</strong> performs the actual authentication. Multiple providers can be configured, such as:</p><blockquote><strong>DaoAuthenticationProvider</strong>: Validates user credentials against a database (e.g., using JDBC or JPA).</blockquote><blockquote><strong>LdapAuthenticationProvider</strong>: Authenticates users via an LDAP (Lightweight Directory Access Protocol) server.</blockquote><blockquote><strong>CasAuthenticationProvider</strong>: Integrates authentication with the CAS (Central Authentication Server) protocol.</blockquote><p><strong>6 - UserDetails Service</strong><br>If the <strong>DaoAuthenticationProvider </strong>is used, it calls the <strong>UserDetailsService</strong> to retrieve user information:</p><blockquote><strong>InMemoryUserDetailsService</strong>: Used for users stored in memory.</blockquote><blockquote><strong>CustomUserDetailsService</strong>: Fetches user details from a database or another data source.<br>After successful retrieval, a <strong>UserDetails </strong>object is returned.</blockquote><p><strong>7 - UserDetails</strong><br>The <strong>UserDetails </strong>object contains the following:</p><blockquote>The username.</blockquote><blockquote>The password.</blockquote><blockquote>The roles assigned to the user (e.g., ROLE_USER, ROLE_ADMIN).</blockquote><p><strong>8 - Authentication Provider (continued)</strong><br>After successfully validating the user information, the <strong>Authentication Provider</strong> returns the authentication result to the <strong>Authentication Manager</strong>.</p><p><strong>9 - Provider Manager</strong><br>The result is evaluated by the <strong>Provider Manager</strong>:</p><p>If authentication is successful, an <strong>Authentication </strong>object is created.<br>If authentication fails, an exception, such as <strong>BadCredentialsException</strong>, is thrown.</p><p>The <strong>SecurityContext</strong> holds the user credentials for the entire application lifecycle.</p><p>It is typically accessed through the SecurityContextHolder.</p><h4>General Workflow:</h4><blockquote>The user sends a request.</blockquote><blockquote>The <strong>Authentication Filter</strong> creates an authentication token and sends it to the <strong>Authentication Manager</strong>.</blockquote><blockquote>The <strong>Authentication Manager</strong> selects the appropriate <strong>Authentication Provider</strong>.</blockquote><blockquote>The <strong>Authentication Provider</strong> authenticates the user using the <strong>UserDetailsService</strong>.</blockquote><blockquote>After successful authentication, the user details are stored in the <strong>Security Context</strong>.</blockquote><p>This workflow is commonly implemented in Spring Boot applications with the help of the spring-boot-starter-security dependency. For customization, components such as UserDetailsService, AuthenticationProvider, or AuthenticationFilter can be overridden.</p><p><strong>Authentication Mechanisms in Spring Security</strong><br>Spring Security provides a rich and comprehensive set of authentication mechanisms. As of 2023, the primary authentication mechanisms supported by Spring Security include:</p><h4><strong>General Authentication Mechanisms:</strong></h4><blockquote><em>Username and Password</em></blockquote><blockquote><em>OAuth 2.0 Login</em></blockquote><blockquote><em>SAML 2.0 Login</em></blockquote><blockquote><em>Central Authentication Server (CAS)</em></blockquote><blockquote><em>Remember Me</em></blockquote><blockquote><em>JAAS (Java Authentication and Authorization Service) Authentication</em></blockquote><blockquote><em>OpenID</em></blockquote><blockquote><em>Pre-Authentication Scenarios</em></blockquote><blockquote><em>X509 Authentication</em></blockquote><h4><strong>Username and Password-Based Authentication Methods</strong></h4><blockquote><strong>Form Login</strong>:<br>This method provides a dedicated interface where users can enter their username and password. Authentication is performed via this user-friendly login form.</blockquote><blockquote><strong>Basic Authentication</strong>:<br>Also known as HTTP Basic Authentication, this method encodes the username and password in Base64 format and sends them with the HTTP request. It is commonly used in API integrations due to its simplicity.</blockquote><blockquote><strong>Digest Authentication</strong>:<br>In this method, HTTP Digest Authentication creates a hash using the username, password, and additional information provided by the server. Authentication is performed using this hash, making it more secure than Basic Authentication.</blockquote><blockquote><strong>JDBC Authentication</strong>:<br>This method is suitable for scenarios where user credentials are stored in a database. During authentication, the system interacts with the database to validate the user’s information.</blockquote><blockquote><strong>LDAP Authentication</strong>:<br>Based on the Lightweight Directory Access Protocol (LDAP), this method integrates with LDAP servers commonly used in organizations for centrally storing user and authorization information. Authentication is performed directly through the LDAP server.</blockquote><h3><strong><em>We will continue with a Spring Boot application example based on username-password authentication.</em></strong></h3><p>Our application focuses on implementing security configurations for <strong>JWT-based authentication</strong> and <strong>authorization</strong> processes. The structure is supported with practical examples, such as managing a simple sales table.</p><p>Users who register and log in to the system can send requests to product tables using a JWT token. This allows them to access product and sales lists and retrieve relevant information. If the credentials are incorrect, the user is presented with informative error messages. Additionally, if the token has expired, access to the related tables is denied, ensuring system security.</p><p>The project is built on the <strong>Spring Boot</strong> framework, with API documentation generated using <strong>Swagger</strong> and requests tested via <strong>Postman</strong>. <strong>MySQL</strong> is used as the database, and the database modules are visualized with <strong>DBeaver</strong>.</p><h4>Application Workflow:</h4><p><strong>User Registration &gt; Login &gt; Operations with JWT</strong></p><h4>User Registration</h4><p>An API endpoint (/register) is created to register users in the system.<br>User details (e.g., username, password) are collected.<br>The password is encrypted using BCryptPasswordEncoder and stored securely.</p><h4>Login with a Registered User</h4><p>The user submits their username and password during login.</p><p>If the login is successful, a <strong>JWT token</strong> is issued to the user.</p><p>This token allows the user to access other protected endpoints.</p><h4>Operations with JWT</h4><p>The user sends the JWT token in the Authorization header of their requests.</p><p>The token is validated, and once the user identity is confirmed, access to the endpoint is granted.</p><p><strong>Describing our application based on a layered architecture will help establish semantic clarity and make the structure more comprehensible.</strong></p><p>1-Entities (User , Product , Sale)</p><p>2-Repository(UserRepository,ProductRepository,SaleRepository)</p><p>3-Service(ProductService,UserService)</p><p>4-Controller(AuthController, ProductController)</p><p>5-Configuration (SecurityConfig,JwtAuthenticationFilter)</p><p>6-Domain(LoginRequest,RegisterRequest)</p><p>7-Util(JwtTokenUtil)</p><p><strong>The Package Hierarchy of Our Application Is as Follows:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*K42wBjHDII0SK8lJn6MaUQ.png" /></figure><p><strong>The dependencies used in our project are as follows:</strong></p><pre>&lt;dependencies&gt;<br>  &lt;!-- Spring Boot Starter Dependencies --&gt;<br> <br> &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-security&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;!-- Devtools for Development --&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>   &lt;optional&gt;true&lt;/optional&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;!-- Testing Dependencies --&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-security-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;!-- Database Dependency --&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;com.mysql&lt;/groupId&gt;<br>   &lt;artifactId&gt;mysql-connector-j&lt;/artifactId&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;!-- JWT Dependencies --&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>   &lt;artifactId&gt;jjwt-api&lt;/artifactId&gt;<br>   &lt;version&gt;0.11.5&lt;/version&gt; &lt;!-- or latest --&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>   &lt;artifactId&gt;jjwt-impl&lt;/artifactId&gt;<br>   &lt;version&gt;0.11.5&lt;/version&gt; &lt;!-- or latest --&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>  &lt;/dependency&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;io.jsonwebtoken&lt;/groupId&gt;<br>   &lt;artifactId&gt;jjwt-jackson&lt;/artifactId&gt;<br>   &lt;version&gt;0.11.5&lt;/version&gt; &lt;!-- or latest --&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;!-- Lombok for Boilerplate Code --&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;<br>   &lt;artifactId&gt;lombok&lt;/artifactId&gt;<br>   &lt;scope&gt;provided&lt;/scope&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;!-- Swagger Dependencies--&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springdoc&lt;/groupId&gt;<br>   &lt;artifactId&gt;springdoc-openapi-starter-webmvc-ui&lt;/artifactId&gt;<br>   &lt;version&gt;2.1.0&lt;/version&gt;<br>  &lt;/dependency&gt;<br> &lt;/dependencies&gt;</pre><p>In the properties file of our application, database connection definitions, JPA configurations, and Swagger configurations are provided.</p><p><strong>application.properties file;</strong></p><pre>spring.application.name=com.timeissecuritytime<br><br>spring.datasource.url=jdbc:mysql://localhost:3307/springsecurityexamples?useSSL=false&amp;allowPublicKeyRetrieval=true&amp;serverTimezone=UTC<br>spring.datasource.username=root<br>spring.datasource.password=test1234<br>spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver<br><br><br>spring.jpa.hibernate.ddl-auto=update<br>spring.jpa.show-sql=true<br>spring.jpa.properties.hibernate.format_sql=true<br>spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect<br><br><br>springdoc.swagger-ui.path=/swagger-ui.html<br>springdoc.api-docs.path=/v3/api-docs</pre><p><strong>You should make database-specific updates in this section.</strong></p><p>According to the layered architecture model, I will first share my entities and the SQL code associated with them.</p><p>User.java (Entity)</p><pre>package com.timeissecuritytime.entity;<br><br>import lombok.*;<br>import jakarta.persistence.*;<br><br>@Entity<br>@Data<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class User {<br> @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    private String username;<br>    private String password;<br>}</pre><p>user db’s sql code;</p><pre>CREATE TABLE `user` (<br>  `id` bigint NOT NULL AUTO_INCREMENT,<br>  `username` varchar(255) NOT NULL,<br>  `password` varchar(255) NOT NULL,<br>  PRIMARY KEY (`id`),<br>  UNIQUE KEY `username` (`username`)<br>) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf16;</pre><p>The <strong>User</strong> table is designed to store the username and password information of users registered in the system. This table is directly linked to the DTOs (Data Transfer Objects) and entities used within the application. The relationship between the database table and the DTOs ensures seamless data flow between the application layers, enabling efficient mapping of database records to objects used in the service and controller layers.</p><p>Product.java (Entity)</p><pre>package com.timeissecuritytime.entity;<br><br>import lombok.Data;<br>import jakarta.persistence.*;<br>import jakarta.persistence.Entity;<br>import jakarta.persistence.GeneratedValue;<br><br>@Entity<br>@Data<br>public class Product {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    private String productName;<br>    private String productDescription;<br>    private Double price;<br>    private Integer stockQuantity;<br>}</pre><p>Product db’s sql code;</p><pre>CREATE TABLE `product` (<br>  `id` BIGINT NOT NULL AUTO_INCREMENT,<br>  `product_name` VARCHAR(255) NOT NULL,<br>  `product_description` TEXT,<br>  `price` DOUBLE NOT NULL,<br>  `stock_quantity` INT NOT NULL,<br>  PRIMARY KEY (`id`)<br>) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;</pre><p>Sale (Entity)</p><pre>package com.timeissecuritytime.entity;<br><br>import jakarta.persistence.Entity;<br>import jakarta.persistence.GeneratedValue;<br>import jakarta.persistence.GenerationType;<br>import jakarta.persistence.Id;<br>import jakarta.persistence.JoinColumn;<br>import jakarta.persistence.ManyToOne;<br>import lombok.Data;<br><br>@Entity<br>@Data<br>public class Sale {<br>    @Id<br>    @GeneratedValue(strategy = GenerationType.IDENTITY)<br>    private Long id;<br>    @ManyToOne<br>    @JoinColumn(name = &quot;product_id&quot;)<br>    private Product product;<br>    private Integer saleQuantity;<br>    private java.util.Date saleDate;<br>}</pre><p>Sale db’s sql code;</p><pre>CREATE TABLE `sale` (<br>  `id` BIGINT NOT NULL AUTO_INCREMENT,<br>  `product_id` BIGINT NOT NULL,<br>  `sale_quantity` INT NOT NULL,<br>  `sale_date` DATETIME NOT NULL,<br>  PRIMARY KEY (`id`),<br>  KEY `product_id` (`product_id`),<br>  CONSTRAINT `sales_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`) ON DELETE CASCADE ON UPDATE CASCADE<br>) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;</pre><p>The Product and Sale entities are not the primary focus of this article. However, we created these entities to support some endpoints that are only accessible to logged-in users. This allows us to demonstrate JWT usage in a practical context and highlight access control mechanisms through services built around these entities.</p><p>The repositories used in our application include <strong>ProductRepository</strong>, <strong>UserRepository</strong>, and <strong>SaleRepository</strong>.</p><pre>package com.timeissecuritytime.repository;<br><br><br>import com.timeissecuritytime.entity.Product;<br>import org.springframework.data.jpa.repository.JpaRepository;<br>import org.springframework.stereotype.Repository;<br>@Repository<br>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {<br>}</pre><pre>package com.timeissecuritytime.repository;<br>import com.timeissecuritytime.entity.Sale;<br>import org.springframework.data.jpa.repository.JpaRepository;<br>import org.springframework.stereotype.Repository;<br>import java.util.List;<br>@Repository<br>public interface SaleRepository extends JpaRepository&lt;Sale, Long&gt; {<br>    List&lt;Sale&gt; findByProductId(Long productId);<br>}</pre><pre>package com.timeissecuritytime.repository;<br>import java.util.Optional;<br>import org.springframework.data.jpa.repository.JpaRepository;<br>import com.timeissecuritytime.entity.User;<br><br>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>    Optional&lt;User&gt; findByUsername(String username);<br>}</pre><p>Data instance for product and sale tables.</p><pre>INSERT INTO `product` (`product_name`, `product_description`, `price`, `stock_quantity`)<br>VALUES <br>(&#39;Laptop&#39;, &#39;High-performance gaming laptop&#39;, 1500.00, 10),<br>(&#39;Smartphone&#39;, &#39;Latest model smartphone with advanced features&#39;, 999.99, 20);<br><br>INSERT INTO `sale` (`product_id`, `sale_quantity`, `sale_date`)<br>VALUES <br>(1, 2, &#39;2025-01-28 12:00:00&#39;),<br>(2, 1, &#39;2025-01-28 13:30:00&#39;);</pre><p>Now, we move on to defining the service files of our project.</p><p>UserService.java</p><pre>package com.timeissecuritytime.service;<br><br>import lombok.RequiredArgsConstructor;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.security.core.userdetails.UserDetailsService;<br>import org.springframework.security.core.userdetails.UsernameNotFoundException;<br>import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;<br>import org.springframework.stereotype.Service;<br>import com.timeissecuritytime.entity.User;<br>import com.timeissecuritytime.repository.UserRepository;<br>import com.timeissecuritytime.Constants;<br><br>@RequiredArgsConstructor<br>@Service<br>public class UserService implements UserDetailsService {<br><br>    private final UserRepository userRepository;<br>    private final BCryptPasswordEncoder bCryptPasswordEncoder;<br><br>    public User registerUser(String username, String password) {<br>        User user = new User();<br>        user.setUsername(username);<br>        user.setPassword(bCryptPasswordEncoder.encode(password));<br>        return userRepository.save(user);<br>    }<br><br>    @Override<br>    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<br>        User user = userRepository.findByUsername(username)<br>                .orElseThrow(() -&gt; new UsernameNotFoundException(Constants.USER_NOT_FOUND + username));<br><br>        return org.springframework.security.core.userdetails.User<br>                .builder()<br>                .username(user.getUsername())<br>                .password(user.getPassword())<br>                .roles(&quot;USER&quot;)<br>                .build();<br>    }<br><br>    public User authenticateUser(String username, String password) {<br>        User user = userRepository.findByUsername(username)<br>                .orElseThrow(() -&gt; new UsernameNotFoundException(Constants.USER_NOT_FOUND + username));<br><br>        if (!bCryptPasswordEncoder.matches(password, user.getPassword())) {<br>            throw new IllegalArgumentException(Constants.INVALID_PASSWORD);<br>        }<br>        return user;<br>    }<br>}</pre><h4>Key Methods in the UserService Class and Their Technical Functionality</h4><p><strong>registerUser(String username, String password)</strong></p><blockquote><strong>Purpose: </strong>To register a new user and securely store their password.<br><strong>Technical Workflow:</strong><br>A User object is created, and the username from the parameters is assigned to it.<br>The password is encrypted (hashed) using BCryptPasswordEncoder and set in the user object.<br>The user object is saved to the database via userRepository.save(user).<br>Use Case: Called during user registration, ensuring secure password storage.</blockquote><p><strong>loadUserByUsername(String username) (Implementation of Spring Security’s UserDetailsService)</strong></p><blockquote><strong>Purpose: </strong>To load user details and return a UserDetails object compatible with Spring Security’s authentication mechanisms.<br><strong>Technical Workflow:</strong><br>The user is searched in the database using <strong>userRepository.findByUsername(username)</strong>.<br>If the user is not found, a <strong>UsernameNotFoundException </strong>is thrown.<br>If the user is found, a <strong>UserDetails </strong>object is created using Spring Security’s User class. This object includes the username, password, and a default role (<strong>USER</strong>).<br>Use Case:<strong> Automatically invoked during Spring Security’s authentication process.</strong></blockquote><p><strong>authenticateUser(String username, String password)</strong></p><blockquote><strong>Purpose:</strong> To validate the user’s login credentials.<br><strong>Technical Workflow:</strong><br>The user is searched in the database using <strong>userRepository.findByUsername(username)</strong>. If not found, a <strong>UsernameNotFoundException </strong>is thrown.<br>The provided password is compared with the stored hashed password using <strong>BCryptPasswordEncoder.matches.</strong><br>If the passwords do not match, an <strong>IllegalArgumentException </strong>is thrown.<br>If validation is successful, the <strong>User </strong>object is returned.<br>Use Case: Manually invoked to verify the correctness of user credentials.</blockquote><p><strong>registerUser: Registers the user, hashes the password, and stores it securely.<br>loadUserByUsername: Provides a UserDetails object for Spring Security’s authentication process.<br>authenticateUser: Manually validates user credentials, useful when custom authentication logic is required.</strong></p><p><strong><em>These methods are designed to provide an integrated user authentication and authorization framework with Spring Security.</em></strong></p><p>ProductService.java</p><pre>package com.timeissecuritytime.service;<br><br>import com.timeissecuritytime.entity.Product;<br>import com.timeissecuritytime.entity.Sale;<br>import com.timeissecuritytime.repository.ProductRepository;<br>import com.timeissecuritytime.repository.SaleRepository;<br>import com.timeissecuritytime.Constants;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.security.access.prepost.PreAuthorize;<br>import org.springframework.stereotype.Service;<br>import org.springframework.transaction.annotation.Transactional;<br>import java.util.List;<br><br>@Service<br>@RequiredArgsConstructor<br>public class ProductService {<br><br>    private final ProductRepository productRepository;<br>    private final SaleRepository saleRepository;<br><br>    @PreAuthorize(&quot;hasRole(&#39;USER&#39;)&quot;)<br>    @Transactional(readOnly = true)<br>    public List&lt;Product&gt; findAllProducts() {<br>        return productRepository.findAll();<br>    }<br><br>    @Transactional(readOnly = true)<br>    public Product findProductById(Long id) {<br>        return productRepository.findById(id)<br>                .orElseThrow(() -&gt; new RuntimeException(Constants.PRODUCT_NOT_FOUND + id));<br>    }<br><br>    @Transactional<br>    @PreAuthorize(&quot;hasRole(&#39;ADMIN&#39;)&quot;)<br>    public Product saveProduct(Product product) {<br>        return productRepository.save(product);<br>    }<br><br>    @Transactional(readOnly = true)<br>    @PreAuthorize(&quot;hasRole(&#39;USER&#39;)&quot;)<br>    public List&lt;Sale&gt; findSalesByProductId(Long productId) {<br>        return saleRepository.findByProductId(productId);<br>    }<br>}</pre><p>This section includes basic service methods for processing product and sales data.</p><p><strong>findAllProducts():</strong> Lists all products and can only be accessed by users with the <strong>USER </strong>role.<br><strong>findProductById(Long id):</strong> Finds a product by its ID. Throws an error if the product is not found.<br><strong>saveProduct(Product product):</strong> Saves a new product and is only accessible to users with the <strong>ADMIN </strong>role.<br><strong>findSalesByProductId(Long productId):</strong> Lists sales related to a specific product and can only be accessed by users with the <strong>USER </strong>role.</p><p><strong><em>This class is not directly related to the main topic of the article, which is authentication and authorization. However, it has been included to demonstrate access control through the provided APIs.</em></strong></p><p>Now, we move on to defining the Controller files of our project.</p><h4>AuthController.java</h4><pre>package com.timeissecuritytime.controller;<br><br>import lombok.RequiredArgsConstructor;<br><br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.*;<br><br>import com.timeissecuritytime.util.JwtTokenUtil;<br>import com.timeissecuritytime.domain.LoginRequest;<br>import com.timeissecuritytime.domain.RegisterRequest;<br>import com.timeissecuritytime.entity.User;<br>import com.timeissecuritytime.service.UserService;<br>import com.timeissecuritytime.Constants;<br><br>@RestController<br>@RequestMapping(&quot;/api/auth&quot;)<br>@RequiredArgsConstructor<br>public class AuthController {<br>    private final UserService userService;<br>    private final JwtTokenUtil jwtTokenUtil;<br><br>    @PostMapping(&quot;/register&quot;)<br>    public ResponseEntity&lt;?&gt; register(@RequestBody RegisterRequest registerRequest) {<br>        userService.registerUser(registerRequest.getUsername(), registerRequest.getPassword());<br>        return ResponseEntity.ok(Constants.REGISTRATION_SUCCESS);<br>    }<br><br>    @PostMapping(&quot;/login&quot;)<br>    public ResponseEntity&lt;?&gt; login(@RequestBody LoginRequest loginRequest) {<br>        User user = userService.authenticateUser(loginRequest.getUsername(), loginRequest.getPassword());<br>        String token = jwtTokenUtil.generateToken(user.getUsername());<br>        return ResponseEntity.ok(String.format(Constants.TOKEN_RESPONSE, token));<br>    }<br>}</pre><p>The AuthController class provides API endpoints for user registration and login.</p><p><strong>/register (POST):</strong> Accepts a registration request from the user and creates a new user via the UserService. Upon successful completion, it returns a success message.</p><p><strong>/login (POST):</strong> Validates the user’s login credentials. After authentication, it generates a JWT token using JwtTokenUtil and returns it to the user.</p><p><strong><em>This class serves as a basic controller for managing the application’s authentication processes.</em></strong></p><h4>ProductController</h4><pre>package com.timeissecuritytime.controller;<br><br>import com.timeissecuritytime.entity.Product;<br>import com.timeissecuritytime.entity.Sale;<br>import com.timeissecuritytime.service.ProductService;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.*;<br><br>import java.util.List;<br><br>@RestController<br>@RequestMapping(&quot;/api/products&quot;)<br>@RequiredArgsConstructor<br>public class ProductController {<br><br>    private final ProductService productService;<br><br>    @GetMapping(&quot;/all&quot;)<br>    public ResponseEntity&lt;List&lt;Product&gt;&gt; getAllProducts() {<br>        return ResponseEntity.ok(productService.findAllProducts());<br>    }<br><br>    @GetMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;Product&gt; getProductById(@PathVariable Long id) {<br>        return ResponseEntity.ok(productService.findProductById(id));<br>    }<br><br>    @PostMapping(&quot;/add&quot;)<br>    public ResponseEntity&lt;Product&gt; addProduct(@RequestBody Product product) {<br>        return ResponseEntity.ok(productService.saveProduct(product));<br>    }<br><br>    @GetMapping(&quot;/sales/{productId}&quot;)<br>    public ResponseEntity&lt;List&lt;Sale&gt;&gt; getSalesByProductId(@PathVariable Long productId) {<br>        return ResponseEntity.ok(productService.findSalesByProductId(productId));<br>    }<br>}</pre><p>The ProductController class provides API endpoints for managing products and sales.</p><p><strong>/all (GET): </strong>Lists all products.<br><strong>/{id} (GET): </strong>Returns the product with the specified ID.<br><strong>/add (POST):</strong> Adds and saves a new product.<br><strong>/sales/{productId} (GET):</strong> Lists sales associated with the specified product ID.<br><strong><em>This class serves as a basic controller for accessing product and sales data.</em></strong></p><p>Now, we move on to defining the <strong>configuration </strong>files of our project.</p><h4><strong>JwtAuthenticationFilter</strong></h4><pre>package com.timeissecuritytime.configuration;<br><br>import java.io.IOException;<br>import java.util.Optional;<br><br>import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;<br>import org.springframework.security.core.context.SecurityContextHolder;<br>import org.springframework.security.core.userdetails.UserDetails;<br>import org.springframework.stereotype.Component;<br>import org.springframework.web.filter.OncePerRequestFilter;<br><br>import com.timeissecuritytime.service.UserService;<br>import com.timeissecuritytime.util.JwtTokenUtil;<br>import com.timeissecuritytime.Constants;<br><br>import jakarta.servlet.FilterChain;<br>import jakarta.servlet.ServletException;<br>import jakarta.servlet.http.HttpServletRequest;<br>import jakarta.servlet.http.HttpServletResponse;<br><br>@Component<br>public class JwtAuthenticationFilter extends OncePerRequestFilter {<br><br>    private final JwtTokenUtil jwtTokenUtil;<br>    private final UserService userService;<br><br>    public JwtAuthenticationFilter(JwtTokenUtil jwtTokenUtil, UserService userService) {<br>        this.jwtTokenUtil = jwtTokenUtil;<br>        this.userService = userService;<br>    }<br><br>    @Override<br>    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)<br>            throws ServletException, IOException {<br>        try {<br>            Optional&lt;String&gt; tokenOptional = extractToken(request);<br>            if (tokenOptional.isPresent()) {<br>                String token = tokenOptional.get();<br>                if (jwtTokenUtil.validateToken(token)) {<br>                    setAuthentication(token);<br>                } else {<br>                    handleInvalidToken(response);<br>                    return;<br>                }<br>            }<br>        } catch (Exception e) {<br>            handleFilterException(response, e);<br>            return;<br>        }<br>        filterChain.doFilter(request, response);<br>    }<br><br>    private Optional&lt;String&gt; extractToken(HttpServletRequest request) {<br>        return Optional.ofNullable(request.getHeader(Constants.AUTHORIZATION_HEADER))<br>                .filter(header -&gt; header.startsWith(Constants.BEARER_PREFIX))<br>                .map(header -&gt; header.substring(Constants.BEARER_PREFIX.length()));<br>    }<br><br>    private void setAuthentication(String token) {<br>        String username = jwtTokenUtil.extractUsername(token);<br>        UserDetails userDetails = userService.loadUserByUsername(username);<br>        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(<br>                userDetails, null, userDetails.getAuthorities());<br>        SecurityContextHolder.getContext().setAuthentication(authentication);<br>    }<br><br>    private void handleInvalidToken(HttpServletResponse response) throws IOException {<br>        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);  <br>        response.getWriter().write(Constants.INVALID_TOKEN_MESSAGE);<br>    }<br><br>    private void handleFilterException(HttpServletResponse response, Exception e) throws IOException {<br>        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);  <br>        response.getWriter().write(Constants.UNEXPECTED_ERROR_MESSAGE);<br>    }<br>}</pre><p><strong>The JwtAuthenticationFilter class is a custom Spring Security filter responsible for JWT (JSON Web Token) validation and authentication.</strong></p><p><strong>doFilterInternal Method:</strong>Extracts the JWT from the Authorization header in incoming requests.<br>If the token is valid, it resolves the username using <strong>JwtTokenUtil </strong>and performs authentication.<br>If an invalid token is detected or an error occurs, it responds with an appropriate HTTP status code and message.</p><p><strong>extractToken Method:</strong>Retrieves the token by stripping the <strong>Bearer </strong>prefix from the Authorization header.</p><p><strong>setAuthentication Method:</strong>Loads UserDetails using the username extracted from the token.<br>Stores the user’s authentication details in the <strong>SecurityContext</strong>, ensuring the user is authenticated throughout the request lifecycle.</p><p><strong>handleInvalidToken and handleFilterException Methods: </strong>Respond with appropriate error messages and status codes for invalid tokens or unexpected errors.</p><p><strong><em>This class executes once per HTTP request and centrally manages the JWT validation process.</em></strong></p><p>JwtTokenUtil</p><pre>package com.timeissecuritytime.configuration;<br><br>import io.jsonwebtoken.*;<br>import io.jsonwebtoken.security.Keys;<br>import lombok.RequiredArgsConstructor;<br><br>import java.util.Date;<br>import java.util.Optional;<br><br>import javax.crypto.SecretKey;<br><br>import org.springframework.stereotype.Component;<br><br>@RequiredArgsConstructor<br>@Component<br>public class JwtTokenUtil {<br><br>    private static final SecretKey SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256);<br>    private static final long EXPIRATION_TIME = 86400000; // One-day<br><br>    public String generateToken(String username) {<br>        return Jwts.builder()<br>            .setSubject(username)<br>            .setIssuedAt(new Date())<br>            .setExpiration(calculateExpirationDate())<br>            .signWith(SECRET_KEY, SignatureAlgorithm.HS256)<br>            .compact();<br>    }<br><br>    public boolean validateToken(String token) {<br>        return parseClaims(token)<br>                .map(this::isTokenValid)<br>                .orElse(false);<br>    }<br><br>    public String extractUsername(String token) {<br>        return parseClaims(token)<br>                .map(Claims::getSubject)<br>                .orElse(null);<br>    }<br><br>    private Date calculateExpirationDate() {<br>        return new Date(System.currentTimeMillis() + EXPIRATION_TIME);<br>    }<br><br>    private Optional&lt;Claims&gt; parseClaims(String token) {<br>        try {<br>            return Optional.of(Jwts.parserBuilder()<br>                    .setSigningKey(SECRET_KEY)<br>                    .build()<br>                    .parseClaimsJws(token)<br>                    .getBody());<br>        } catch (JwtException e) {<br>            return Optional.empty();<br>        }<br>    }<br><br>    private boolean isTokenValid(Claims claims) {<br>        Date expirationDate = claims.getExpiration();<br>        return expirationDate != null &amp;&amp; !expirationDate.before(new Date());<br>    }<br>}</pre><p>The JwtTokenUtil class is a utility designed for handling JWT operations (generation, validation, and parsing). Below is a detailed technical explanation of its methods:</p><h4><strong>generateToken(String username) Method:</strong></h4><p><strong>setSubject(username): </strong>Sets the username as the sub claim in the token.<br><strong>setIssuedAt(new Date()):</strong> Sets the token’s issue date.<br><strong>setExpiration(calculateExpirationDate()):</strong> Calculates and adds the expiration date.<br><strong>signWith(SECRET_KEY, SignatureAlgorithm.HS256):</strong> Signs the token using the HS256 algorithm and SECRET_KEY.<br>compact(): Returns the final JWT as a string.<br><em>Creates a signed JWT with the username and expiration details.</em></p><h4>validateToken(String token) Method:</h4><p><strong>parseClaims(token): </strong>Parses the Claims object from the token.<br><strong>isTokenValid(claims):</strong> Checks if the token’s expiration date is valid.<br>Returns Optional.empty() if the token is invalid.<br>Validates the token and returns true or false.</p><h4><strong>extractUsername(String token) Method:</strong></h4><p><strong>parseClaims(token): </strong>Parses the Claims object from the token.<br>Claims::getSubject: Extracts the sub (username) claim from the Claims.</p><p><strong>ExpirationDate Method:</strong><br>System.currentTimeMillis() + EXPIRATION_TIME: Adds one day to the current timestamp to calculate the expiration date.<br>Returns the expiration date as a Date object.</p><p><strong>parseClaims(String token) Method:</strong><br>Jwts.parserBuilder().setSigningKey(SECRET_KEY).build().parseClaimsJws(token):<br>Parses the token to extract the Claims object.<br>Throws JwtException for invalid tokens and returns Optional.empty().<br>Returns all claims (Claims) within the token.</p><p><strong>isTokenValid(Claims claims) Method:</strong><br>claims.getExpiration(): Retrieves the expiration date of the token.<br>!expirationDate.before(new Date()): Verifies if the expiration date has not passed.<br>Returns true if the token is still valid, otherwise false.</p><p><strong><em>This class ensures secure and centralized handling of JWT operations, making it integral to JWT-based authentication systems.</em></strong></p><p>SecurityConfig</p><pre>package com.timeissecuritytime.configuration;<br><br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;<br>import org.springframework.security.config.http.SessionCreationPolicy;<br>import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;<br>import org.springframework.security.web.SecurityFilterChain;<br>import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;<br><br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.security.config.annotation.web.builders.HttpSecurity;<br>import org.springframework.security.config.http.SessionCreationPolicy;<br>import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;<br>import org.springframework.security.web.SecurityFilterChain;<br>import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;<br><br>@Configuration<br>public class SecurityConfig {<br><br>    @Bean<br>    public SecurityFilterChain filterChain(HttpSecurity http, JwtAuthenticationFilter jwtAuthenticationFilter)<br>            throws Exception {<br>        http<br>             .csrf(csrf -&gt; csrf.disable())<br>             .authorizeHttpRequests(auth -&gt; auth<br>                .requestMatchers(<br>                        &quot;/api/auth/**&quot;, <br>                        &quot;/v3/api-docs/**&quot;, <br>                        &quot;/swagger-ui/**&quot;, <br>                        &quot;/swagger-ui.html&quot;, <br>                        &quot;/v3/api-docs/swagger-config&quot;<br>                ).permitAll()  <br>                .anyRequest().authenticated()  <br>            )<br>            <br>            .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)<br>            .sessionManagement(session -&gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));<br><br>        return http.build();<br>    }<br>    @Bean<br>    public BCryptPasswordEncoder passwordEncoder() {<br>        return new BCryptPasswordEncoder();<br>    }<br>}<br><br></pre><p><strong>The SecurityConfig class configures Spring Security for the application. It defines the security rules, authentication mechanisms, and cryptographic settings. Below is a detailed technical breakdown of each part:</strong></p><p><strong>1. filterChain(HttpSecurity http, JwtAuthenticationFilter jwtAuthenticationFilter) Method</strong><br><br>This method defines the core security configuration, including which endpoints are secured, which ones are public, and how security filters are applied.</p><p><strong>csrf(csrf -&gt; csrf.disable())</strong></p><p>Purpose: Disables CSRF (Cross-Site Request Forgery) protection.<br>Reason: Typically disabled for stateless APIs since they don’t use session-based authentication.</p><p><strong>authorizeHttpRequests(auth -&gt; auth…)</strong></p><p>Purpose: Configures access rules for HTTP endpoints.<br>Details:<br>requestMatchers(…): Specifies the endpoints that are public (accessible without authentication). Examples:<br>/api/auth/**: Authentication-related endpoints (e.g., login, register).<br>/v3/api-docs/**, /swagger-ui/**: Publicly accessible Swagger API documentation.<br><strong>anyRequest().authenticated(): </strong>All other endpoints require authentication.</p><p><strong>addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)</strong></p><p>Purpose: Adds a custom filter (JwtAuthenticationFilter) to the security filter chain.<br>Details: The JwtAuthenticationFilter processes incoming requests to validate JWT tokens before the default UsernamePasswordAuthenticationFilter is triggered.</p><p><strong>sessionManagement(session -&gt; session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))</strong></p><p>Purpose: Configures session management.<br>Details: Sets the session creation policy to STATELESS, ensuring that no sessions are created. This is essential for stateless authentication (e.g., JWT-based systems).<br>Returns:<br>The fully configured SecurityFilterChain object, which defines how Spring Security handles requests.</p><p><strong>2. passwordEncoder() Method</strong><br>Purpose:<br>Defines the password encoder used to hash and verify passwords.</p><p>Key Configuration:</p><p>Returns an instance of BCryptPasswordEncoder, which is a strong hashing function for secure password storage.<br>Ensures that plaintext passwords are never stored and instead are hashed with a one-way algorithm.</p><h4>Summary of Key Concepts in SecurityConfig:</h4><p><strong>Stateless Security: </strong>The application uses JWT tokens for authentication, so no session state is maintained on the server. This is achieved through SessionCreationPolicy.STATELESS.<br><strong>Filter Chain:</strong>Custom filters like JwtAuthenticationFilter are integrated into the Spring Security filter chain to handle JWT validation.</p><p><strong>Endpoint Security:</strong>Public endpoints (/api/auth/**, /swagger-ui/**) are explicitly permitted. All other endpoints require authenticated access.<br><strong>Password Encryption:</strong>Passwords are encrypted using BCryptPasswordEncoder to ensure security during storage.</p><p><strong>Security Flow:</strong><br>A request enters the application and is processed by the SecurityFilterChain.<br>If the request matches a public endpoint, it is permitted without authentication.<br>For all other endpoints:</p><p>Our file where constants are defined, the class we use for global error handling, and our domain objects are as follows.</p><p>domain objects;</p><pre>package com.timeissecuritytime.domain;<br>import lombok.Data;<br>@Data<br>public class LoginRequest {<br>    private String username;<br>    private String password;<br>}</pre><pre>package com.timeissecuritytime.domain;<br>import lombok.Data;<br>@Data<br>public class RegisterRequest {<br>    private String username;<br>    private String password;<br>}</pre><p>GlobalExceptionHandler;</p><pre>package com.timeissecuritytime.controller;<br><br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.ExceptionHandler;<br>import org.springframework.web.bind.annotation.RestControllerAdvice;<br><br>@RestControllerAdvice<br>public class GlobalExceptionHandler {<br>    @ExceptionHandler(Exception.class)<br>    public ResponseEntity&lt;?&gt; handleException(Exception e) {<br>        return ResponseEntity.badRequest().body(e.getMessage());<br>    }<br>}</pre><p>Constants</p><pre>package com.timeissecuritytime;<br><br>public class Constants {<br>    public static final String REGISTRATION_SUCCESS = &quot;User successfully registered!&quot;;<br>    public static final String TOKEN_RESPONSE = &quot;Token: %s&quot;;<br>    public static final String PRODUCT_NOT_FOUND = &quot;Product not found: &quot;;<br>    public static final String USER_NOT_FOUND = &quot;User not found: &quot;;<br>    public static final String INVALID_PASSWORD = &quot;Invalid password!&quot;;<br>    public static final String AUTHORIZATION_HEADER = &quot;Authorization&quot;;<br>    public static final String BEARER_PREFIX = &quot;Bearer &quot;;<br>    public static final String INVALID_TOKEN_MESSAGE = &quot;{\&quot;error\&quot;: \&quot;Token has expired or is invalid. Please log in again.\&quot;}&quot;;<br>    public static final String UNEXPECTED_ERROR_MESSAGE = &quot;{\&quot;error\&quot;: \&quot;An unexpected error occurred.\&quot;}&quot;;<br>}</pre><p>Now, we will use Postman to interact with our application. First, we will <strong>register</strong> a user via the register operation. Next, we will log in using the login operation to obtain a JWT token. Then, we will attempt to list products without using the token and observe the authorization error we receive. Finally, we will demonstrate that by providing a valid token, we can successfully access our services and list the products. These steps will help you understand the security configurations and token-based access control implemented in our application.</p><p><strong>1-User Registration: Signing Up via the Register Operation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*QNYYhri5aYRzcItoIE5__Q.png" /></figure><p><strong>2-Logging In and Obtaining a JWT Token</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xuVrPyvMPGMvXe63wtDGDg.png" /></figure><p><strong>3-Attempting to List Products Without a Token and Observing the Error</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*lKpwarkFcfOv5JUh-t_ABQ.png" /></figure><p><strong>4-Accessing Services with a Valid Token</strong></p><p>Authentication token type was defined;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f8KnS6r9K3N5m_M2lG8iLQ.png" /></figure><p>After that , i called service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*Ezp4U9NfUJ4IJ_2eLmP_-Q.png" /></figure><blockquote>In this article, we explored the JWT-based authentication and authorization processes in Spring Security in detail. Additionally, we highlighted the importance of building a security-focused infrastructure by structuring our application using a layered architecture. While explaining the interactions between each component of the application, we used sample code to make these processes more understandable. This setup will help you develop a secure and sustainable system by preventing unauthorized access.</blockquote><blockquote>Thank you for reading our article. Follow us for more content and feel free to share your thoughts and feedback. Your opinions are very valuable to us!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ef395683b28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Fundamentals of WebSocket and Dynamic Multi-Chat Application with Java]]></title>
            <link>https://medium.com/@ibrahimerdogandev/the-fundamentals-of-websocket-and-dynamic-multi-chat-application-with-java-f34d82d19130?source=rss-3936637a32ae------2</link>
            <guid isPermaLink="false">https://medium.com/p/f34d82d19130</guid>
            <category><![CDATA[server-client-setup]]></category>
            <category><![CDATA[java-socket-basicsing]]></category>
            <category><![CDATA[java-socket-programming]]></category>
            <category><![CDATA[network-programming]]></category>
            <category><![CDATA[websocket-usage]]></category>
            <dc:creator><![CDATA[İbrahim Erdoğan]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 22:44:48 GMT</pubDate>
            <atom:updated>2025-01-11T22:51:51.887Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ep1FCh1BXvilTlH3AlY4GA.jpeg" /></figure><p>WebSocket is a flexible and efficient communication protocol that provides full-duplex communication channels and establishes connections using the TCP protocol.</p><p>It is designed to be implemented in web servers and web browsers. In 2011, it was standardized as RFC 6455.</p><p>WebSockets establish a persistent connection between the client and the server.</p><p>With its bi-directional communication model, data can be mutually transferred between the client and the server at any time. This feature distinguishes it from the HTTP protocol.</p><h3>What Are the Advantages of Using WebSocket?</h3><p>The advantages of using WebSocket can be summarized as follows:</p><ol><li><em>Real-Time Communication:<br></em>WebSocket enables real-time communication between the server and the client. This forms the foundation for faster and more responsive applications.</li><li><em>Low Latency:<br></em>Compared to HTTP, WebSocket has lower latency as it requires fewer header details. This allows data packets to be sent and received faster, making it ideal for applications requiring quick response times.</li><li><em>Reduced Bandwidth Usage:<br></em>WebSocket establishes a persistent connection, reducing unnecessary data exchanges. Once a connection is established, data transfer continues until the connection is terminated. Unlike HTTP, which creates a new connection for each request, WebSocket uses significantly less bandwidth.</li><li><em>Bi-Directional Communication:<br></em>WebSocket supports two-way communication between the server and the client. This allows the server to actively push data to the client, distinguishing it from HTTP’s request-response model.</li><li><em>Flexible Protocol:<br></em>WebSocket is a flexible protocol that can adapt to a wide range of applications. It is used in various environments, from web applications to IoT devices. Since its message headers are smaller than those transmitted with HTTP, it generates smaller packets and uses fewer resources, making it an efficient protocol.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*de9VVpUpwXsnEilfuVWFww.png" /></figure><p><strong>Overview of the WebSocket Frame</strong><br>The WebSocket frame is a structure at the core of the protocol, enabling real-time and low-latency communication. This framework facilitates data exchange between the client and server, operating with fast, flexible, and minimal protocol overhead in bidirectional communication. The WebSocket frame transports messages in a structured format and serves as the foundation of data transmission.</p><p><strong>Components of the WebSocket Frame</strong></p><p><strong>Header:</strong> Carries the control information of the frame. The header specifies the frame type, whether the message is complete (FIN bit), the length of the payload, and whether it is masked.</p><p><strong>Masking Key:</strong> Frames from the client are masked for data security. The server uses this key to unmask the data.</p><p><strong>Payload:</strong> Contains the actual message content. This content can be text, binary data, or a control message. Depending on the size of the message, the payload can be divided into multiple frames.</p><p>These components make WebSocket a lightweight yet reliable protocol, indispensable for real-time applications.</p><h3>Establishing a Persistent Connection Significantly Reduces Data Transfer Latency</h3><h4>Examples of WebSocket Use Cases:</h4><ul><li><em>Messaging Applications<br>Enables real-time communication between users.</em></li><li><em>Real-Time Games<br>Supports fast and interactive multiplayer gaming experiences.</em></li><li><em>Live Updates<br>Facilitates live updates for stock prices, sports scores, or news feeds.</em></li><li><em>IoT Applications<br>Provides efficient communication between IoT devices and servers.</em></li><li><em>Financial Applications<br>Ensures low-latency data transfer for trading platforms and financial dashboards.</em></li><li><em>Security Systems<br>Allows real-time monitoring and alerting in security systems.</em></li><li><em>Blockchain Applications<br>Enables real-time updates and synchronization in blockchain networks.</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*KOaIOc_1Bj9-Oq4z9bwEqQ.png" /></figure><h3>Basic Socket Programming with Java: Chat Application</h3><p>In this example application, a chat application will be implemented based on the client-server architecture using Core Java.</p><p>This application serves as an example for those who want to learn and practice the basic concepts of socket programming. The application consists of two main components: <strong>ChatSocketServer</strong> and <strong>ChatSocketClient</strong>.</p><h3>1. ChatSocketServer (Server)</h3><p>This component is a class that manages communication between clients and forms the main server-side of the chat application.</p><h4>Responsibilities:</h4><ul><li><em>Listening on a Port:<br></em>Listens to a specific port number (default: 12345) through a ServerSocket.</li><li><em>Handling New Clients:<br></em>Starts a ClientHandler thread for each new client, ensuring independent processing of each client connection.</li><li><em>Message Broadcasting:<br></em>Receives messages from a client and forwards them to all connected clients.</li><li><em>Client Connection Notifications:<br></em>Notifies other clients when a new client joins or leaves the chat.</li></ul><h3>2. ChatSocketClient (Client)</h3><p>This component is the client application that allows users to connect to the server, send messages, and receive messages from other users.</p><h4>Responsibilities:</h4><ul><li>Connecting to the Server:<br>Connects to the specified IP address (127.0.0.1) and port number (12345)</li><li>Sending Messages:<br>Captures messages from the user and sends them to the server.</li><li>Receiving Messages:<br>Listens to messages from the server using a background thread (separate thread) and displays them on the screen.</li></ul><p>1-ChatSocketServer’s code;</p><pre>package com.testsocket;<br><br>import java.io.*;<br>import java.net.*;<br>import java.util.*;<br><br>public class ChatSocketServer {<br><br>    private static final int PORT = 12345;<br>    private static Map&lt;String, PrintWriter&gt; clientWriters = new HashMap&lt;&gt;();<br><br>    public static void main(String[] args) {<br>        System.out.println(&quot;Server is starting...&quot;);<br>        try (ServerSocket serverSocket = new ServerSocket(PORT)) {<br>            while (true) {<br>                Socket clientSocket = serverSocket.accept();<br>                new ClientHandler(clientSocket).start();<br>            }<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br>    }<br><br>    private static class ClientHandler extends Thread {<br>        private Socket socket;<br>        private String username;<br>        private BufferedReader in;<br>        private PrintWriter out;<br><br>        public ClientHandler(Socket socket) {<br>            this.socket = socket;<br>        }<br><br>        public void run() {<br>            try {<br>                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));<br>                out = new PrintWriter(socket.getOutputStream(), true);<br><br>                out.println(&quot;Enter your username:&quot;);<br>                username = in.readLine();<br>                synchronized (clientWriters) {<br>                    clientWriters.put(username, out);<br>                }<br>                System.out.println(username + &quot; has connected.&quot;);<br><br>                // Notify other clients that a user has joined<br>                broadcastMessage(&quot;Server&quot;, username + &quot; has joined the chat.&quot;);<br><br>                // Listen for incoming messages and forward them<br>                String message;<br>                while ((message = in.readLine()) != null) {<br>                    System.out.println(&quot;[&quot; + username + &quot;]: &quot; + message);<br>                    broadcastMessage(username, message);<br>                }<br>            } catch (IOException e) {<br>                e.printStackTrace();<br>            } finally {<br>                <br>                if (username != null) {<br>                    synchronized (clientWriters) {<br>                        clientWriters.remove(username);<br>                    }<br>                    broadcastMessage(&quot;Server&quot;, username + &quot; has left the chat.&quot;);<br>                }<br>                try {<br>                    socket.close();<br>                } catch (IOException e) {<br>                    e.printStackTrace();<br>                }<br>            }<br>        }<br><br>        // Send the message to all clients<br>        private void broadcastMessage(String sender, String message) {<br>            synchronized (clientWriters) {<br>                for (PrintWriter writer : clientWriters.values()) {<br>                    writer.println(&quot;[&quot; + sender + &quot;]: &quot; + message);<br>                }<br>            }<br>        }<br>    }<br>}</pre><h4>Main Components of ChatSocketServer</h4><p><strong>1. ClientHandler:</strong></p><p>An inner class that processes each client connection in a separate thread.</p><p>Responsibilities:</p><ul><li>Stores the username of the client.</li><li>Broadcasts incoming messages from the client to other connected clients.</li><li>Manages the client’s connection, including disconnection handling.</li></ul><h4>2. broadcastMessage:</h4><p>A method used to forward a message received from one client to all other connected clients.</p><p><strong>Key Functions:</strong></p><ul><li>Ensures real-time delivery of messages to all clients in the chat.</li><li>Handles message formatting and avoids sending the message back to the sender.</li></ul><p>2- <strong>ChatSocketClient</strong></p><pre>package com.testsocket;<br><br>import java.io.*;<br>import java.net.*;<br>import java.util.Scanner;<br><br>public class ChatSocketClient {<br><br>    private static final String SERVER_ADDRESS = &quot;127.0.0.1&quot;;<br>    private static final int SERVER_PORT = 12345;<br><br>    public static void main(String[] args) {<br>        try (Socket socket = new Socket(SERVER_ADDRESS, SERVER_PORT)) {<br>            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));<br>            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);<br><br>            Scanner scanner = new Scanner(System.in);<br><br>            // A separate thread to listen for messages from the server<br>            new Thread(() -&gt; {<br>                try {<br>                    String message;<br>                    while ((message = in.readLine()) != null) {<br>                        System.out.println(message);<br>                    }<br>                } catch (IOException e) {<br>                    e.printStackTrace();<br>                }<br>            }).start();<br><br>            // Read user messages and send them to the server<br>            while (true) {<br>                String message = scanner.nextLine();<br>                out.println(message);<br>            }<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><h3>Main Components of ChatSocketClient</h3><p><strong>1. Server Connection</strong></p><p><em>Establishes a connection to the server using IP and port.</em></p><p><strong>2. Input and Output Streams</strong></p><p><em>Manages data exchange between the client and server.</em></p><p><strong>3. Message Listener Thread</strong></p><p><em>Listens for and displays incoming messages from the server.</em></p><p><strong>4. User Input and Message Sending</strong></p><p><em>Captures user input from the console and sends it to the server.</em></p><p><strong>5. Exception Handling</strong></p><p><em>Manages errors like connection failures or I/O issues.</em></p><p><strong>6. Continuous Loop</strong></p><p><em>Keeps the client running to send and receive messages.</em></p><h3><strong>Working Principle of the Application</strong></h3><p><strong>Server Initialization:</strong><br>The ChatSocketServer is started and begins listening on a specified port for new client connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*LSLmQMD8XeG8Ow1qFj4Fxg.png" /></figure><p><strong>Client Connection:</strong><br>The ChatSocketClient is executed, connects to the server, and prompts the user to enter a username.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*EP0vJtFHH2GlDNgrCBwhMw.png" /></figure><p><strong>Messaging:</strong><br>As users type messages, these messages are transmitted through the server to all other connected clients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*LTYsP2u1QUMlV089Lss7gg.png" /></figure><p><strong>Connection Management:</strong><br>When a client disconnects, the server notifies the other clients and releases the resources associated with the disconnected client.</p><p><strong><em>Thank you for reading this article about the WebSocket protocol and basic socket programming! Feel free to share your thoughts and experiences regarding WebSocket or socket programming in the comments. I’d especially love to hear about the projects you’ve developed with this technology or the challenges you’ve faced.</em></strong></p><p><strong><em>If you found this article helpful, don’t forget to like and share it to help it reach more people. Make sure to follow my profile to stay updated on my future articles!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f34d82d19130" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>