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
Role
Enum which can beROLE_USER
orROLE_ADMIN
:
- Add
JJWTUser
Class:
- annotated with
@Entity
,@Table(name="jjwt_users")
,@Data
,@NoArgsConstructor
,@AllArgsConstructor
; - with attributes
id
,name
,login
,password
,roles
.
- Add
JJWTUserRepository
Interface:
- annotated with
@Repository
; - extends
JpaRepository<JJWTUser, String>
; - has the method
Optional<JJWTUser> findByLogin(String login)
;
- Add a value for
api.security.token.secret
inapplication.properties
:
# ===================================================================
# SECURITY
# ===================================================================
api.security.token.secret=chaveSecreta
- Add
JJWTTokenService
Class:
- in the
security
package; - with the attributes
secret
,ISSUER
,EXPIRATION_HOURS
andZONE_OFFSET
; - with the private methods
Instant calculateExpiration()
andAlgorithm getAlgorithm()
; - with public methods
String generateToken(JJWTUser jjwtUser)
andString validateToken(String token)
.
- Add
JJWTUserDetailsService
Class:
- in the
security
package; - 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
JJWTSecurityFilter
Class:
- in the
security
package; - annotated with
@Component
; - extends
OncePerRequestFilter
; - with attributes
jjwtTokenService
andjjwtUserDetailsService
; - with a constructor with injected attributes;
- with a protected method
void doFilterInternal()
; - with a private method
String recoverToken(HttpServletRequest request)
.
- Add
JJWTSecurityConfig
Class:
- in the
security
package; - annotated with
@Configuration
,@EnableWebSecurity
; - with attributes
jjwtSecurityFilter
andjjwtUserDetailsService
; - with a constructor with injected attributes;
- with the public methods
SecurityFilterChain securityFilterChain
,PasswordEncoder passwordEncoder()
,AuthenticationManager authenticationManager
annotated with@Bean
;
- Add records DTOs:
- in the
dtos
package; LoginRequestDTO
containslogin
andpassword
;LoginResponseDTO
containsname
andtoken
;RegisterRequestDTO
containsname
,login
andpassword
;RegisterResponseDTO
containsname
andtoken
.
- Add
AuthService
Interface:
- in the
services
package; - with methods
LoginResponseDTO login(LoginRequestDTO loginRequestDTO)
andRegisterResponseDTO register(RegisterRequestDTO registerRequestDTO)
.
- Add
AuthServiceImpl
Class:
- in the
services
package; - annotated with
@Service
; - implements
AuthService
; - with attributes
PasswordEncoder passwordEncoder
,JJWTUserRepository jjwtUserRepository
andJJWTTokenService jjwtTokenService
; - with a constructor with injected attributes;
- Add
AuthController
Class:
- in the
controllers
package; - annotated with
@RestController
and@RequestMapping("/auth")
; - with the
AuthService authService
attribute; - 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
securityFilterChain
method 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