Code Monkey home page Code Monkey logo

spring-boot-spring-security-jwt-authentication's Introduction

Spring Boot JWT Authentication example with Spring Security & Spring Data JPA

User Registration, User Login and Authorization process.

The diagram shows flow of how we implement User Registration, User Login and Authorization process.

spring-boot-jwt-authentication-spring-security-flow

Spring Boot Server Architecture with Spring Security

You can have an overview of our Spring Boot Server with the diagram below:

spring-boot-jwt-authentication-spring-security-architecture

Dependency

– If you want to use PostgreSQL:

<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <scope>runtime</scope>
</dependency>

– or MySQL:

<dependency>
  <groupId>com.mysql</groupId>
  <artifactId>mysql-connector-j</artifactId>
  <scope>runtime</scope>
</dependency>

Configure Spring Datasource, JPA, App properties

Open src/main/resources/application.properties

  • For PostgreSQL:
spring.datasource.url= jdbc:postgresql://localhost:5432/testdb
spring.datasource.username= postgres
spring.datasource.password= 123

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update

# App Properties
bezkoder.app.jwtSecret= bezKoderSecretKey
bezkoder.app.jwtExpirationMs= 86400000
  • For MySQL
spring.datasource.url=jdbc:mysql://localhost:3306/testdb_spring?useSSL=false
spring.datasource.username=root
spring.datasource.password=123456

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto=update

# App Properties
bezkoder.app.jwtSecret= ======================BezKoder=Spring===========================
bezkoder.app.jwtExpirationMs=86400000

Run Spring Boot application

mvn spring-boot:run

Run following SQL insert statements

INSERT INTO roles(name) VALUES('ROLE_USER');
INSERT INTO roles(name) VALUES('ROLE_MODERATOR');
INSERT INTO roles(name) VALUES('ROLE_ADMIN');

For more detail, please visit:

Secure Spring Boot with Spring Security & JWT Authentication

For MongoDB

Refresh Token

spring-boot-refresh-token-jwt-example-flow

For instruction: Spring Boot Refresh Token with JWT example

More Practice:

Spring Boot JWT Authentication example using HttpOnly Cookie

Spring Boot File upload example with Multipart File

Exception handling: @RestControllerAdvice example in Spring Boot

Spring Boot Repository Unit Test with @DataJpaTest

Spring Boot Pagination & Sorting example

Validation: Spring Boot Validate Request Body

Documentation: Spring Boot and Swagger 3 example

Caching: Spring Boot Redis Cache example

Associations:

Spring Boot One To Many example with Spring JPA, Hibernate

Spring Boot Many To Many example with Spring JPA, Hibernate

JPA One To One example with Spring Boot

Deployment:

Deploy Spring Boot App on AWS – Elastic Beanstalk

Docker Compose Spring Boot and MySQL example

Fullstack Authentication

Spring Boot + Vue.js JWT Authentication

Spring Boot + Angular 8 JWT Authentication

Spring Boot + Angular 10 JWT Authentication

Spring Boot + Angular 11 JWT Authentication

Spring Boot + Angular 12 JWT Authentication

Spring Boot + Angular 13 JWT Authentication

Spring Boot + Angular 14 JWT Authentication

Spring Boot + Angular 15 JWT Authentication

Spring Boot + Angular 16 JWT Authentication

Spring Boot + Angular 17 JWT Authentication

Spring Boot + React JWT Authentication

Fullstack CRUD App

Vue.js + Spring Boot + H2 Embedded database example

Vue.js + Spring Boot + MySQL example

Vue.js + Spring Boot + PostgreSQL example

Angular 8 + Spring Boot + Embedded database example

Angular 8 + Spring Boot + MySQL example

Angular 8 + Spring Boot + PostgreSQL example

Angular 10 + Spring Boot + MySQL example

Angular 10 + Spring Boot + PostgreSQL example

Angular 11 + Spring Boot + MySQL example

Angular 11 + Spring Boot + PostgreSQL example

Angular 12 + Spring Boot + Embedded database example

Angular 12 + Spring Boot + MySQL example

Angular 12 + Spring Boot + PostgreSQL example

Angular 13 + Spring Boot + H2 Embedded Database example

Angular 13 + Spring Boot + MySQL example

Angular 13 + Spring Boot + PostgreSQL example

Angular 14 + Spring Boot + H2 Embedded Database example

Angular 14 + Spring Boot + MySQL example

Angular 14 + Spring Boot + PostgreSQL example

Angular 15 + Spring Boot + H2 Embedded Database example

Angular 15 + Spring Boot + MySQL example

Angular 15 + Spring Boot + PostgreSQL example

Angular 16 + Spring Boot + H2 Embedded Database example

Angular 16 + Spring Boot + MySQL example

Angular 16 + Spring Boot + PostgreSQL example

Angular 17 + Spring Boot + H2 Embedded Database example

Angular 17 + Spring Boot + MySQL example

Angular 17 + Spring Boot + PostgreSQL example

React + Spring Boot + MySQL example

React + Spring Boot + PostgreSQL example

React + Spring Boot + MongoDB example

Run both Back-end & Front-end in one place:

Integrate Angular with Spring Boot Rest API

Integrate React.js with Spring Boot Rest API

Integrate Vue.js with Spring Boot Rest API

spring-boot-spring-security-jwt-authentication's People

Contributors

bezkoder avatar tienbku avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

spring-boot-spring-security-jwt-authentication's Issues

The web application [ROOT] appears to have started a thread named [HikariPool-1 housekeeper] but has failed to stop it. This is very likely to create a memory leak.

2023-06-13T15:35:30.978+05:30 INFO 27060 --- [on(5)-127.0.0.1] inMXBeanRegistrar$SpringApplicationAdmin : Application shutdown requested.
2023-06-13T15:35:31.139+05:30 INFO 27060 --- [on(5)-127.0.0.1] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2023-06-13T15:35:31.152+05:30 WARN 27060 --- [on(5)-127.0.0.1] o.a.c.loader.WebappClassLoaderBase : The web application [ROOT] appears to have started a thread named [HikariPool-1 housekeeper] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
[email protected]/jdk.internal.misc.Unsafe.park(Native Method)
[email protected]/java.util.concurrent.locks.LockSupport.parkNanos(LockSupport.java:252)
[email protected]/java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.awaitNanos(AbstractQueuedSynchronizer.java:1672)
[email protected]/java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1182)
[email protected]/java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:899)
[email protected]/java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1062)
[email protected]/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1122)
[email protected]/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
[email protected]/java.lang.Thread.run(Thread.java:833)
2023-06-13T15:35:31.171+05:30 INFO 27060 --- [on(5)-127.0.0.1] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2023-06-13T15:35:31.176+05:30 INFO 27060 --- [on(5)-127.0.0.1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2023-06-13T15:35:31.199+05:30 INFO 27060 --- [on(5)-127.0.0.1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.

Signup posts generates 401

When trying to create users following the example in the docs I get 401 on posting to /api/auth/signup

SecurityContextHolder

Hi May I ask what is the use of

SecurityContextHolder.getContext().setAuthentication(authentication);

in the AuthController?

I thought JWT was session-less and stateless. Thank you

WebSecurityConfig.java AuthTokenFilter bug

Hi sir, on the WebSecurityConfig java file, the AuthTokenFilter constructor is missing two parameters, jwt utils and user details service.

Can you please assign this issue to me so that I can resolve it.

Thank you.

getting org.springframework.security.authentication.InsufficientAuthenticationException error If I pass unknown api url or method

Hi after implementing the spring security with jwt token it is working as expected with known API urls but when I hit with unknown URL, get 401 authorized error and if any exception is raised at runtime also gets 401 authorized because fo the below exception in Cansole.
getting org. spring framework.security.authentication.InsufficientAuthenticationException

do I need to add any filter in AuthEntryPointJwt under the commence? I just wanted to ignore the authentication filter if there is any unknown API hit that came to the application and should throw the NoHandlerFoundException custom exception error with below handler. how can I do that?

@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity handle(NoHandlerFoundException ex){
return new ResponseEntity<>(APIError.createInstance(HttpStatus.NOT_FOUND.toString(),
List.of(new ErrorDetails(ex.getMessage(),null))), null, HttpStatus.NOT_FOUND);
}

This entire JWT implementation is bad practice

Spring security has had full JWT-support since 2017.

Writing a custom security solution with some sort of custom security filter is bad practice. Thats why there are security standards, to avoid writing custom security solutions.

The spring security documentation has clear instructions on how to handle JWTs and this is not it.

https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html#oauth2resourceserver-jwt-architecture

Role is not found

com.bezkoder.springjwt.controllers.AuthController.lambda$1(AuthController.java:99)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.