Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

Spring Boot Security JWT[java web token] Explained Step by Step-handson

Автор: Global Tamil Mirror

Загружено: 2025-12-19

Просмотров: 20

Описание:

Hi All,
Welcome to Global Tamil Mirror.

This is a fully hands-on tutorial for those who already have some knowledge in Java Spring Boot.
Today, we are going to see how to set up JWT in a Spring Boot application.

This is a simple attempt to present the hands-on without video, so please prepare your prerequisites.

Prerequisites

STS or any other IDE (STS is used here)

JDK 21

Maven

Please be ready with these requirements, then start the hands-on.

Step 1: Create Spring Boot Application using STS

File → New → Spring Starter Project
Enter Name: JWTDemo
Select Maven
Java Version: 21
Keep other options as it is
Group: com.jwt.demo (anything you wish)

Add dependency:

Spring Web

We will add remaining later

Finish this.

Right-click pom.xml → Run As → Maven Install
Once it is successful
Right-click application → Run As → Spring Boot App

JWT: Java Web Token for REST API
Step 2: Create Simple REST API

Right-click com.jwt.demo main application

Create package named com.jwt.demo.controller

Create class named BankController

Add annotation @RestController

Add annotation @RequestMapping("/bank")

Create method getData()
Annotate with @GetMapping("/getData")

Save, re-run, and check using Postman

REST API is working fine.

Step 3: Start JWT Setup

Add annotation @EnableWebSecurity in main class

If not detected, add dependency spring-boot-starter-security
You can remove version from pom.xml because it is auto compatible

Import required packages

Re-run application and test using Postman.
It shows 401 Unauthorized.

This happens because web security is enabled and configuration is not completed.

You will see generated security password in console, for example:
508a5b51-0b09-4330-8610-dff83e6a2225

Use:

Username: user (default Spring Security username)

Password: generated password

Authorization Type: Basic Auth

Now you can access the REST API.

Spring Security and JWT

This is the default security implementation by Spring Security.
There are many types of authentication, and one of them is JWT.
Authorization type will be Bearer Token / JWT Bearer.

JWT Basic Flow
First Request

/auth/login API should be allowed without JWT

JWT is generated after login

Flow:

auth/login → Spring Security → permitAll

SecurityContextPersistenceFilter loads empty security context

UsernamePasswordAuthenticationFilter intercepts login

Reads username and password

Creates authentication token

Passes it to AuthenticationManager

AuthenticationManager:

Loads username and password from DB

If password matches → authentication success

Else → 401 Unauthorized

Spring Security configuration handles JWT API requests and stateless session management.
JWT is stateless, so server does not store JWT.

Second and Further Requests

Example:
http://localhost:8081/bank/getData

Authorization: Bearer JWT token

Request goes to JwtAuthFilter and returns response only if token is valid.

Step 4: Create Security Configuration

Create package com.jwt.demo.security
Create class SecurityConfig
Annotate with @Configuration and @EnableWebSecurity

Step 5: Create JwtAuthFilter

Create class JwtAuthFilter
Extend OncePerRequestFilter
Implement doFilterInternal()

This filter is invoked after JWT is generated.

Step 6: Create JwtUtil Helper Class

Create class JwtUtil.java
Annotate with @Component
Add secret key

JwtAuthFilter is now completed.

Step 7: Create AuthRequest DTO

Create class AuthRequest for JSON input
Use Lombok and add dependency

Step 8: Create AuthController

Create class AuthController
It checks username and password internally, extracts roles, and generates JWT if authentication is successful.

Step 9: Additional Configurations

Add AuthenticationManager bean in SecurityConfig

Create UserConfig class

Add UserDetailsService method

Step 10: Test JWT Login API

POST http://localhost:8081/auth/login

Request body:
{ "username": "prabha", "password": "123456" }

JWT token is generated successfully.

Step 11: Test Protected API

GET http://localhost:8081/bank/getData

Authorization: Bearer JWT token

Response: Login Success

Token Expiry

If token expires, API returns 403 Forbidden.
Generate token again and API works.

JWT setup is working fine.

Final Notes

Please go through the setup class by class and very slowly.
You should have some basic Spring Boot knowledge.

This tutorial has no audio, but the steps are detailed enough.
Steps are uploaded in description, and GitHub repo URL is also shared.

Happy Learning 😊
Bye 👋

Please Subscribe, Like, and Learn more from here.

Spring Boot Security JWT[java web token] Explained Step by Step-handson

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

“Spring Boot Deployment on AWS EC2 Using Docker 2025 | Complete Guide”

“Spring Boot Deployment on AWS EC2 Using Docker 2025 | Complete Guide”

Чем ОПАСЕН МАХ? Разбор приложения специалистом по кибер безопасности

Чем ОПАСЕН МАХ? Разбор приложения специалистом по кибер безопасности

📌 Dataset & Pandas in Data Science | Data Handling with Python Pandas

📌 Dataset & Pandas in Data Science | Data Handling with Python Pandas

Мебельная фурнитура которую вы не поняли

Мебельная фурнитура которую вы не поняли

ПОТАПЕНКО:

ПОТАПЕНКО: "Будьте готовы! Это надолго". Что будет в РФ, ПРЯМАЯ ЛИНИЯ Путина, ЧТО ДАЛЬШЕ

Музыка для работы - Deep Focus Mix для программирования, кодирования

Музыка для работы - Deep Focus Mix для программирования, кодирования

Суперважная разработка для правительства | Зарплата 50к рублей (English subtitles) @Максим Кац

Суперважная разработка для правительства | Зарплата 50к рублей (English subtitles) @Максим Кац

Spring Boot

Spring Boot

Первый контакт УЖЕ произошел, но мы этого НЕ ЗАМЕТИЛИ! | Михаил Никитин, Борис Штерн

Первый контакт УЖЕ произошел, но мы этого НЕ ЗАМЕТИЛИ! | Михаил Никитин, Борис Штерн

Session против JWT: различия, о которых вы могли не знать!

Session против JWT: различия, о которых вы могли не знать!

Git Bash Tutorial: Upload Spring Boot Project to GitHub (Beginner Friendly)

Git Bash Tutorial: Upload Spring Boot Project to GitHub (Beginner Friendly)

КАЦ: Путин бежит, в Кремле паника.(НЕТ). Эксперимент Валерия Соловья, дело Долиной, казус Надеждина

КАЦ: Путин бежит, в Кремле паника.(НЕТ). Эксперимент Валерия Соловья, дело Долиной, казус Надеждина

Kubernetes — Простым Языком на Понятном Примере

Kubernetes — Простым Языком на Понятном Примере

«ИСТРЕБЛЕНИЕ НАШИХ ГЕНЕРАЛОВ». Z-ники в бешенстве, что Украине опять удалось убить генерала в Москве

«ИСТРЕБЛЕНИЕ НАШИХ ГЕНЕРАЛОВ». Z-ники в бешенстве, что Украине опять удалось убить генерала в Москве

Что такое Rest API (http)? Soap? GraphQL? Websockets? RPC (gRPC, tRPC). Клиент - сервер. Вся теория

Что такое Rest API (http)? Soap? GraphQL? Websockets? RPC (gRPC, tRPC). Клиент - сервер. Вся теория

Microsoft Intune: от нуля до героя

Microsoft Intune: от нуля до героя

КАК УСТРОЕН TCP/IP?

КАК УСТРОЕН TCP/IP?

Spring Boot CI/CD to AWS EC2 using Docker & GitHub Actions (Complete Guide)

Spring Boot CI/CD to AWS EC2 using Docker & GitHub Actions (Complete Guide)

14 ГЛАВНЫХ НЕЙРОСЕТЕЙ 2025 ГОДА

14 ГЛАВНЫХ НЕЙРОСЕТЕЙ 2025 ГОДА

Spring Boot 4 значительно упростил REST-запросы! 🚀

Spring Boot 4 значительно упростил REST-запросы! 🚀

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]