Java project with Spring and Gradle for authentication using Java JSON Web Token (JJWT).
The steps of project implementation:
- Create project (in IntelliJ) with:
- Java language (17);
- Spring Framework (6.2.3);
- Dependencies: Web, Security, DevTools, JPA, H2, Lombok, Actuator, Validation.
- Add Auth0 java-jwt dependency obtained from
Maven Repository
for the
build.gradle(orpom.xml) file:
implementation group: 'com.auth0', name: 'java-jwt', version: '4.4.0'or
implementation 'com.auth0:java-jwt:4.4.0'or
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>- Add datasource, jpa and h2 settings in
application.properties:
# ===================================================================
# APPLICATION
# ===================================================================
spring.application.name=Java-Spring-JJWT
# ===================================================================
# DATASOURCE AND H2 DATABASE
# ===================================================================
# H2 - Datasource
spring.datasource.url=jdbc:h2:mem:jjwtapp
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=admin
spring.datasource.password=admin
# H2 - Console
spring.h2.console.enabled=true
spring.h2.console.path=/h2
# Hibernate
# spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
#spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.hibernate.ddl-auto=update
# http://localhost:8080/h2/- Add
RoleEnum which can beROLE_USERorROLE_ADMIN:
- Add
JJWTUserClass:
- annotated with
@Entity,@Table(name="jjwt_users"),@Data,@NoArgsConstructor,@AllArgsConstructor; - with attributes
id,name,login,password,roles.
- Add
JJWTUserRepositoryInterface:
- annotated with
@Repository; - extends
JpaRepository<JJWTUser, String>; - has the method
Optional<JJWTUser> findByLogin(String login);
- Add a value for
api.security.token.secretinapplication.properties:
# ===================================================================
# SECURITY
# ===================================================================
api.security.token.secret=chaveSecreta- Add
JJWTTokenServiceClass:
- in the
securitypackage; - with the attributes
secret,ISSUER,EXPIRATION_HOURSandZONE_OFFSET; - with the private methods
Instant calculateExpiration()andAlgorithm getAlgorithm(); - with public methods
String generateToken(JJWTUser jjwtUser)andString validateToken(String token).
- Add
JJWTUserDetailsServiceClass:
- in the
securitypackage; - implements
UserDetailsService; - with attribute
JJWTUserRepository jjwtUserRepository; - with a constructor with the injected attribute;
- with a public method
UserDetails loadUserByUsername(String username); - with a private method
Collection<? extends GrantedAuthority> mapRolesToAuthorities(Set<Role> roles).
- Add
JJWTSecurityFilterClass:
- in the
securitypackage; - annotated with
@Component; - extends
OncePerRequestFilter; - with attributes
jjwtTokenServiceandjjwtUserDetailsService; - with a constructor with injected attributes;
- with a protected method
void doFilterInternal(); - with a private method
String recoverToken(HttpServletRequest request).
- Add
JJWTSecurityConfigClass:
- in the
securitypackage; - annotated with
@Configuration,@EnableWebSecurity; - with attributes
jjwtSecurityFilterandjjwtUserDetailsService; - with a constructor with injected attributes;
- with the public methods
SecurityFilterChain securityFilterChain,PasswordEncoder passwordEncoder(),AuthenticationManager authenticationManagerannotated with@Bean;
- Add records DTOs:
- in the
dtospackage; LoginRequestDTOcontainsloginandpassword;LoginResponseDTOcontainsnameandtoken;RegisterRequestDTOcontainsname,loginandpassword;RegisterResponseDTOcontainsnameandtoken.
- Add
AuthServiceInterface:
- in the
servicespackage; - with methods
LoginResponseDTO login(LoginRequestDTO loginRequestDTO)andRegisterResponseDTO register(RegisterRequestDTO registerRequestDTO).
- Add
AuthServiceImplClass:
- in the
servicespackage; - annotated with
@Service; - implements
AuthService; - with attributes
PasswordEncoder passwordEncoder,JJWTUserRepository jjwtUserRepositoryandJJWTTokenService jjwtTokenService; - with a constructor with injected attributes;
- Add
AuthControllerClass:
- in the
controllerspackage; - annotated with
@RestControllerand@RequestMapping("/auth"); - with the
AuthService authServiceattribute; - with a constructor with the injected attribute;
- with the methods:
ResponseEntity<LoginResponseDTO> login(@RequestBody LoginRequestDTO loginRequestDTO)to@PostMapping("/login");ResponseEntity<RegisterResponseDTO> register(@RequestBody RegisterRequestDTO registerRequestDTO)for@PostMapping("/register").ResponseEntity<String> authenticatedUsers()for@GetMapping("/users");ResponseEntity<String> authenticatedAdmins()for@GetMapping("/admins").
-
Add routes and their permissions in the
securityFilterChainmethod ofJJWTSecurityConfig. -
Test routes, authentication and authorization with POSTMAN:
Maven Repository - Auth0 - Java JWT: https://mvnrepository.com/artifact/com.auth0/java-jwt/4.4.0
Fernanda Kipper | Dev - PROJETO FULLSTACK COM LOGIN USANDO SPRING SECURITY + JWT | BACKEND:
https://www.youtube.com/watch?v=tJCyNV1G0P4 |
https://github.com/Fernanda-Kipper/login-app-backend/tree/main
Fernanda Kipper | Dev - Autenticação e Autorização com Spring Security, JWT Tokens e Roles: https://www.youtube.com/watch?v=5w-YCcOjPD0
GitBook - Auth Database - Gleyson Sampaio: https://glysns.gitbook.io/spring-framework/spring-security/auth-database
GitBook - JWT - JSON Web Token - Gleyson Sampaio: https://glysns.gitbook.io/spring-framework/spring-security/spring-security-e-jwt













