├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── src ├── main │ ├── java │ │ └── com │ │ │ └── alibou │ │ │ └── security │ │ │ ├── token │ │ │ ├── TokenType.java │ │ │ ├── TokenRepository.java │ │ │ └── Token.java │ │ │ ├── book │ │ │ ├── BookRepository.java │ │ │ ├── BookRequest.java │ │ │ ├── BookService.java │ │ │ ├── BookController.java │ │ │ └── Book.java │ │ │ ├── user │ │ │ ├── UserRepository.java │ │ │ ├── ChangePasswordRequest.java │ │ │ ├── Permission.java │ │ │ ├── UserController.java │ │ │ ├── UserService.java │ │ │ ├── User.java │ │ │ └── Role.java │ │ │ ├── auth │ │ │ ├── AuthenticationRequest.java │ │ │ ├── RegisterRequest.java │ │ │ ├── AuthenticationResponse.java │ │ │ ├── AuthenticationController.java │ │ │ └── AuthenticationService.java │ │ │ ├── demo │ │ │ ├── DemoController.java │ │ │ ├── AdminController.java │ │ │ └── ManagementController.java │ │ │ ├── auditing │ │ │ └── ApplicationAuditAware.java │ │ │ ├── config │ │ │ ├── LogoutService.java │ │ │ ├── OpenApiConfig.java │ │ │ ├── ApplicationConfig.java │ │ │ ├── JwtAuthenticationFilter.java │ │ │ ├── JwtService.java │ │ │ └── SecurityConfiguration.java │ │ │ └── SecurityApplication.java │ └── resources │ │ └── application.yml └── test │ └── java │ └── com │ └── alibou │ └── security │ └── SecurityApplicationTests.java ├── http ├── http-test.http ├── jpa-auditing.http └── change-password.http ├── .gitignore ├── docker-compose.yml ├── README.md ├── pom.xml ├── mvnw.cmd ├── mvnw ├── LICENSE └── jwt-security.drawio /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ali-bouali/spring-boot-3-jwt-security/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/token/TokenType.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.token; 2 | 3 | public enum TokenType { 4 | BEARER 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/book/BookRepository.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.book; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | public interface BookRepository extends JpaRepository { 6 | } 7 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar 3 | -------------------------------------------------------------------------------- /src/test/java/com/alibou/security/SecurityApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class SecurityApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/user/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.user; 2 | 3 | import java.util.Optional; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface UserRepository extends JpaRepository { 7 | 8 | Optional findByEmail(String email); 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/book/BookRequest.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.book; 2 | 3 | import lombok.Builder; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | @Getter 8 | @Setter 9 | @Builder 10 | public class BookRequest { 11 | 12 | private Integer id; 13 | private String author; 14 | private String isbn; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/user/ChangePasswordRequest.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.user; 2 | 3 | import lombok.Builder; 4 | import lombok.Getter; 5 | import lombok.Setter; 6 | 7 | @Getter 8 | @Setter 9 | @Builder 10 | public class ChangePasswordRequest { 11 | 12 | private String currentPassword; 13 | private String newPassword; 14 | private String confirmationPassword; 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/auth/AuthenticationRequest.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.auth; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Builder; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | @Data 9 | @Builder 10 | @AllArgsConstructor 11 | @NoArgsConstructor 12 | public class AuthenticationRequest { 13 | 14 | private String email; 15 | String password; 16 | } 17 | -------------------------------------------------------------------------------- /http/http-test.http: -------------------------------------------------------------------------------- 1 | ### Register User 2 | POST http://localhost:8080/api/v1/auth/register 3 | Content-Type: application/json 4 | 5 | { 6 | "firstname": "Ali", 7 | "lastname": "Bouali", 8 | "email": "alibou21@mail.com", 9 | "password": "password", 10 | "role": "ADMIN" 11 | } 12 | 13 | > {% client.global.set("auth-token", response.body.access_token); %} 14 | 15 | ### Query the Demo endpoint 16 | GET http://localhost:8080/api/v1/demo-controller 17 | Authorization: Bearer {{auth-token}} 18 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/auth/RegisterRequest.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.auth; 2 | 3 | import com.alibou.security.user.Role; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | @Data 10 | @Builder 11 | @AllArgsConstructor 12 | @NoArgsConstructor 13 | public class RegisterRequest { 14 | 15 | private String firstname; 16 | private String lastname; 17 | private String email; 18 | private String password; 19 | private Role role; 20 | } 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/auth/AuthenticationResponse.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.auth; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | @Data 10 | @Builder 11 | @AllArgsConstructor 12 | @NoArgsConstructor 13 | public class AuthenticationResponse { 14 | 15 | @JsonProperty("access_token") 16 | private String accessToken; 17 | @JsonProperty("refresh_token") 18 | private String refreshToken; 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/user/Permission.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.user; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | 6 | @RequiredArgsConstructor 7 | public enum Permission { 8 | 9 | ADMIN_READ("admin:read"), 10 | ADMIN_UPDATE("admin:update"), 11 | ADMIN_CREATE("admin:create"), 12 | ADMIN_DELETE("admin:delete"), 13 | MANAGER_READ("management:read"), 14 | MANAGER_UPDATE("management:update"), 15 | MANAGER_CREATE("management:create"), 16 | MANAGER_DELETE("management:delete") 17 | 18 | ; 19 | 20 | @Getter 21 | private final String permission; 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/demo/DemoController.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.demo; 2 | 3 | import io.swagger.v3.oas.annotations.Hidden; 4 | import org.springframework.http.ResponseEntity; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | @RestController 10 | @RequestMapping("/api/v1/demo-controller") 11 | @Hidden 12 | public class DemoController { 13 | 14 | @GetMapping 15 | public ResponseEntity sayHello() { 16 | return ResponseEntity.ok("Hello from secured endpoint"); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/token/TokenRepository.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.token; 2 | 3 | import java.util.List; 4 | import java.util.Optional; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.Query; 7 | 8 | public interface TokenRepository extends JpaRepository { 9 | 10 | @Query(value = """ 11 | select t from Token t inner join User u\s 12 | on t.user.id = u.id\s 13 | where u.id = :id and (t.expired = false or t.revoked = false)\s 14 | """) 15 | List findAllValidTokenByUser(Integer id); 16 | 17 | Optional findByToken(String token); 18 | } 19 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | spring: 2 | datasource: 3 | url: jdbc:postgresql://localhost:5432/jwt_security 4 | username: username 5 | password: password 6 | driver-class-name: org.postgresql.Driver 7 | jpa: 8 | hibernate: 9 | ddl-auto: create-drop 10 | show-sql: false 11 | properties: 12 | hibernate: 13 | format_sql: true 14 | database: postgresql 15 | database-platform: org.hibernate.dialect.PostgreSQLDialect 16 | 17 | application: 18 | security: 19 | jwt: 20 | secret-key: 404E635266556A586E3272357538782F413F4428472B4B6250645367566B5970 21 | expiration: 86400000 # a day 22 | refresh-token: 23 | expiration: 604800000 # 7 days 24 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/book/BookService.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.book; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import org.springframework.stereotype.Service; 5 | 6 | import java.util.List; 7 | 8 | @Service 9 | @RequiredArgsConstructor 10 | public class BookService { 11 | 12 | private final BookRepository repository; 13 | 14 | public void save(BookRequest request) { 15 | var book = Book.builder() 16 | .id(request.getId()) 17 | .author(request.getAuthor()) 18 | .isbn(request.getIsbn()) 19 | .build(); 20 | repository.save(book); 21 | } 22 | 23 | public List findAll() { 24 | return repository.findAll(); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | postgres: 3 | container_name: postgres-sql 4 | image: postgres 5 | environment: 6 | POSTGRES_USER: username 7 | POSTGRES_PASSWORD: password 8 | PGDATA: /data/postgres 9 | volumes: 10 | - postgres:/data/postgres 11 | ports: 12 | - "5432:5432" 13 | networks: 14 | - postgres 15 | restart: unless-stopped 16 | 17 | pgadmin: 18 | container_name: pgadmin 19 | image: dpage/pgadmin4 20 | environment: 21 | PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-pgadmin4@pgadmin.org} 22 | PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-admin} 23 | PGADMIN_CONFIG_SERVER_MODE: 'False' 24 | volumes: 25 | - pgadmin:/var/lib/pgadmin 26 | ports: 27 | - "5050:80" 28 | networks: 29 | - postgres 30 | restart: unless-stopped 31 | 32 | networks: 33 | postgres: 34 | driver: bridge 35 | 36 | volumes: 37 | postgres: 38 | pgadmin: -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/user/UserController.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.user; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import org.springframework.http.ResponseEntity; 5 | import org.springframework.web.bind.annotation.PatchMapping; 6 | import org.springframework.web.bind.annotation.RequestBody; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | import java.security.Principal; 11 | 12 | @RestController 13 | @RequestMapping("/api/v1/users") 14 | @RequiredArgsConstructor 15 | public class UserController { 16 | 17 | private final UserService service; 18 | 19 | @PatchMapping 20 | public ResponseEntity changePassword( 21 | @RequestBody ChangePasswordRequest request, 22 | Principal connectedUser 23 | ) { 24 | service.changePassword(request, connectedUser); 25 | return ResponseEntity.ok().build(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /http/jpa-auditing.http: -------------------------------------------------------------------------------- 1 | ### Register User 2 | POST http://localhost:8080/api/v1/auth/register 3 | Content-Type: application/json 4 | 5 | { 6 | "firstname": "Ali", 7 | "lastname": "Bouali", 8 | "email": "alibou@mail.com", 9 | "password": "password", 10 | "role": "ADMIN" 11 | } 12 | 13 | > {% client.global.set("auth-token", response.body.access_token); %} 14 | 15 | 16 | ###Create a new book 17 | POST http://localhost:8080/api/v1/books 18 | Authorization: Bearer {{auth-token}} 19 | Content-Type: application/json 20 | 21 | { 22 | "author": "Alibou", 23 | "isbn": "12345" 24 | } 25 | 26 | ### Query Books 27 | GET http://localhost:8080/api/v1/books 28 | Authorization: Bearer {{auth-token}} 29 | 30 | ### Update one book 31 | POST http://localhost:8080/api/v1/books 32 | Authorization: Bearer {{auth-token}} 33 | Content-Type: application/json 34 | 35 | { 36 | "id": 1, 37 | "author": "Alibou 2", 38 | "isbn": "12345" 39 | } 40 | 41 | 42 | ### Query the Books one more time 43 | GET http://localhost:8080/api/v1/books 44 | Authorization: Bearer {{auth-token}} 45 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/book/BookController.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.book; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import org.springframework.http.ResponseEntity; 5 | import org.springframework.web.bind.annotation.GetMapping; 6 | import org.springframework.web.bind.annotation.PostMapping; 7 | import org.springframework.web.bind.annotation.RequestBody; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | import java.util.List; 12 | 13 | @RestController 14 | @RequestMapping("/api/v1/books") 15 | @RequiredArgsConstructor 16 | public class BookController { 17 | 18 | private final BookService service; 19 | 20 | @PostMapping 21 | public ResponseEntity save( 22 | @RequestBody BookRequest request 23 | ) { 24 | service.save(request); 25 | return ResponseEntity.accepted().build(); 26 | } 27 | 28 | @GetMapping 29 | public ResponseEntity> findAllBooks() { 30 | return ResponseEntity.ok(service.findAll()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/token/Token.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.token; 2 | 3 | import com.alibou.security.user.User; 4 | import jakarta.persistence.Column; 5 | import jakarta.persistence.Entity; 6 | import jakarta.persistence.EnumType; 7 | import jakarta.persistence.Enumerated; 8 | import jakarta.persistence.FetchType; 9 | import jakarta.persistence.GeneratedValue; 10 | import jakarta.persistence.Id; 11 | import jakarta.persistence.JoinColumn; 12 | import jakarta.persistence.ManyToOne; 13 | import lombok.AllArgsConstructor; 14 | import lombok.Builder; 15 | import lombok.Data; 16 | import lombok.NoArgsConstructor; 17 | 18 | @Data 19 | @Builder 20 | @NoArgsConstructor 21 | @AllArgsConstructor 22 | @Entity 23 | public class Token { 24 | 25 | @Id 26 | @GeneratedValue 27 | public Integer id; 28 | 29 | @Column(unique = true) 30 | public String token; 31 | 32 | @Enumerated(EnumType.STRING) 33 | public TokenType tokenType = TokenType.BEARER; 34 | 35 | public boolean revoked; 36 | 37 | public boolean expired; 38 | 39 | @ManyToOne(fetch = FetchType.LAZY) 40 | @JoinColumn(name = "user_id") 41 | public User user; 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/auditing/ApplicationAuditAware.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.auditing; 2 | 3 | import com.alibou.security.user.User; 4 | import org.springframework.data.domain.AuditorAware; 5 | import org.springframework.security.authentication.AnonymousAuthenticationToken; 6 | import org.springframework.security.core.Authentication; 7 | import org.springframework.security.core.context.SecurityContextHolder; 8 | 9 | import java.util.Optional; 10 | 11 | public class ApplicationAuditAware implements AuditorAware { 12 | @Override 13 | public Optional getCurrentAuditor() { 14 | Authentication authentication = 15 | SecurityContextHolder 16 | .getContext() 17 | .getAuthentication(); 18 | if (authentication == null || 19 | !authentication.isAuthenticated() || 20 | authentication instanceof AnonymousAuthenticationToken 21 | ) { 22 | return Optional.empty(); 23 | } 24 | 25 | User userPrincipal = (User) authentication.getPrincipal(); 26 | return Optional.ofNullable(userPrincipal.getId()); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Spring Boot 3.0 Security with JWT Implementation 2 | This project demonstrates the implementation of security using Spring Boot 3.0 and JSON Web Tokens (JWT). It includes the following features: 3 | 4 | ## Features 5 | * User registration and login with JWT authentication 6 | * Password encryption using BCrypt 7 | * Role-based authorization with Spring Security 8 | * Customized access denied handling 9 | * Logout mechanism 10 | * Refresh token 11 | 12 | ## Technologies 13 | * Spring Boot 3.0 14 | * Spring Security 15 | * JSON Web Tokens (JWT) 16 | * BCrypt 17 | * Maven 18 | 19 | ## Getting Started 20 | To get started with this project, you will need to have the following installed on your local machine: 21 | 22 | * JDK 17+ 23 | * Maven 3+ 24 | 25 | 26 | To build and run the project, follow these steps: 27 | 28 | * Clone the repository: `git clone https://github.com/ali-bouali/spring-boot-3-jwt-security.git` 29 | * Navigate to the project directory: cd spring-boot-security-jwt 30 | * Add database "jwt_security" to postgres 31 | * Build the project: mvn clean install 32 | * Run the project: mvn spring-boot:run 33 | 34 | -> The application will be available at http://localhost:8080. 35 | -------------------------------------------------------------------------------- /http/change-password.http: -------------------------------------------------------------------------------- 1 | ### Register User 2 | POST http://localhost:8080/api/v1/auth/register 3 | Content-Type: application/json 4 | 5 | { 6 | "firstname": "Ali", 7 | "lastname": "Bouali", 8 | "email": "alibou@mail.com", 9 | "password": "password", 10 | "role": "ADMIN" 11 | } 12 | 13 | > {% client.global.set("auth-token", response.body.access_token); %} 14 | 15 | ### Query the Demo endpoint 16 | GET http://localhost:8080/api/v1/demo-controller 17 | Authorization: Bearer {{auth-token}} 18 | 19 | 20 | ### Change the password 21 | PATCH http://localhost:8080/api/v1/users 22 | Content-Type: application/json 23 | Authorization: Bearer {{auth-token}} 24 | 25 | { 26 | "currentPassword": "password", 27 | "newPassword": "newPassword", 28 | "confirmationPassword": "newPassword" 29 | } 30 | 31 | ### Login again and update the token 32 | POST http://localhost:8080/api/v1/auth/authenticate 33 | Content-Type: application/json 34 | 35 | { 36 | "email": "alibou@mail.com", 37 | "password": "newPassword" 38 | } 39 | 40 | > {% client.global.set("new-auth-token", response.body.access_token); %} 41 | 42 | 43 | ### Query the Demo endpoint after password change 44 | GET http://localhost:8080/api/v1/demo-controller 45 | Authorization: Bearer {{new-auth-token}} 46 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/demo/AdminController.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.demo; 2 | 3 | import io.swagger.v3.oas.annotations.Hidden; 4 | import org.springframework.security.access.prepost.PreAuthorize; 5 | import org.springframework.web.bind.annotation.DeleteMapping; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.PostMapping; 8 | import org.springframework.web.bind.annotation.PutMapping; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | @RestController 13 | @RequestMapping("/api/v1/admin") 14 | @PreAuthorize("hasRole('ADMIN')") 15 | public class AdminController { 16 | 17 | @GetMapping 18 | @PreAuthorize("hasAuthority('admin:read')") 19 | public String get() { 20 | return "GET:: admin controller"; 21 | } 22 | @PostMapping 23 | @PreAuthorize("hasAuthority('admin:create')") 24 | @Hidden 25 | public String post() { 26 | return "POST:: admin controller"; 27 | } 28 | @PutMapping 29 | @PreAuthorize("hasAuthority('admin:update')") 30 | @Hidden 31 | public String put() { 32 | return "PUT:: admin controller"; 33 | } 34 | @DeleteMapping 35 | @PreAuthorize("hasAuthority('admin:delete')") 36 | @Hidden 37 | public String delete() { 38 | return "DELETE:: admin controller"; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/config/LogoutService.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.config; 2 | 3 | import com.alibou.security.token.TokenRepository; 4 | import jakarta.servlet.http.HttpServletRequest; 5 | import jakarta.servlet.http.HttpServletResponse; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.security.core.Authentication; 8 | import org.springframework.security.core.context.SecurityContextHolder; 9 | import org.springframework.security.web.authentication.logout.LogoutHandler; 10 | import org.springframework.stereotype.Service; 11 | 12 | @Service 13 | @RequiredArgsConstructor 14 | public class LogoutService implements LogoutHandler { 15 | 16 | private final TokenRepository tokenRepository; 17 | 18 | @Override 19 | public void logout( 20 | HttpServletRequest request, 21 | HttpServletResponse response, 22 | Authentication authentication 23 | ) { 24 | final String authHeader = request.getHeader("Authorization"); 25 | final String jwt; 26 | if (authHeader == null ||!authHeader.startsWith("Bearer ")) { 27 | return; 28 | } 29 | jwt = authHeader.substring(7); 30 | var storedToken = tokenRepository.findByToken(jwt) 31 | .orElse(null); 32 | if (storedToken != null) { 33 | storedToken.setExpired(true); 34 | storedToken.setRevoked(true); 35 | tokenRepository.save(storedToken); 36 | SecurityContextHolder.clearContext(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/user/UserService.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.user; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 5 | import org.springframework.security.crypto.password.PasswordEncoder; 6 | import org.springframework.stereotype.Service; 7 | 8 | import java.security.Principal; 9 | 10 | @Service 11 | @RequiredArgsConstructor 12 | public class UserService { 13 | 14 | private final PasswordEncoder passwordEncoder; 15 | private final UserRepository repository; 16 | public void changePassword(ChangePasswordRequest request, Principal connectedUser) { 17 | 18 | var user = (User) ((UsernamePasswordAuthenticationToken) connectedUser).getPrincipal(); 19 | 20 | // check if the current password is correct 21 | if (!passwordEncoder.matches(request.getCurrentPassword(), user.getPassword())) { 22 | throw new IllegalStateException("Wrong password"); 23 | } 24 | // check if the two new passwords are the same 25 | if (!request.getNewPassword().equals(request.getConfirmationPassword())) { 26 | throw new IllegalStateException("Password are not the same"); 27 | } 28 | 29 | // update the password 30 | user.setPassword(passwordEncoder.encode(request.getNewPassword())); 31 | 32 | // save the new password 33 | repository.save(user); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/auth/AuthenticationController.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.auth; 2 | 3 | import jakarta.servlet.http.HttpServletRequest; 4 | import jakarta.servlet.http.HttpServletResponse; 5 | import lombok.RequiredArgsConstructor; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.web.bind.annotation.PostMapping; 8 | import org.springframework.web.bind.annotation.RequestBody; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | import java.io.IOException; 13 | 14 | @RestController 15 | @RequestMapping("/api/v1/auth") 16 | @RequiredArgsConstructor 17 | public class AuthenticationController { 18 | 19 | private final AuthenticationService service; 20 | 21 | @PostMapping("/register") 22 | public ResponseEntity register( 23 | @RequestBody RegisterRequest request 24 | ) { 25 | return ResponseEntity.ok(service.register(request)); 26 | } 27 | @PostMapping("/authenticate") 28 | public ResponseEntity authenticate( 29 | @RequestBody AuthenticationRequest request 30 | ) { 31 | return ResponseEntity.ok(service.authenticate(request)); 32 | } 33 | 34 | @PostMapping("/refresh-token") 35 | public void refreshToken( 36 | HttpServletRequest request, 37 | HttpServletResponse response 38 | ) throws IOException { 39 | service.refreshToken(request, response); 40 | } 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/book/Book.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.book; 2 | 3 | import jakarta.persistence.Column; 4 | import jakarta.persistence.Entity; 5 | import jakarta.persistence.EntityListeners; 6 | import jakarta.persistence.GeneratedValue; 7 | import jakarta.persistence.Id; 8 | import lombok.AllArgsConstructor; 9 | import lombok.Builder; 10 | import lombok.Data; 11 | import lombok.NoArgsConstructor; 12 | import org.springframework.data.annotation.CreatedBy; 13 | import org.springframework.data.annotation.CreatedDate; 14 | import org.springframework.data.annotation.LastModifiedBy; 15 | import org.springframework.data.annotation.LastModifiedDate; 16 | import org.springframework.data.jpa.domain.support.AuditingEntityListener; 17 | 18 | import java.time.LocalDateTime; 19 | 20 | @Data 21 | @Builder 22 | @NoArgsConstructor 23 | @AllArgsConstructor 24 | @Entity 25 | @EntityListeners(AuditingEntityListener.class) 26 | public class Book { 27 | 28 | @Id 29 | @GeneratedValue 30 | private Integer id; 31 | private String author; 32 | private String isbn; 33 | 34 | @CreatedDate 35 | @Column( 36 | nullable = false, 37 | updatable = false 38 | ) 39 | private LocalDateTime createDate; 40 | 41 | @LastModifiedDate 42 | @Column(insertable = false) 43 | private LocalDateTime lastModified; 44 | 45 | 46 | @CreatedBy 47 | @Column( 48 | nullable = false, 49 | updatable = false 50 | ) 51 | private Integer createdBy; 52 | 53 | @LastModifiedBy 54 | @Column(insertable = false) 55 | private Integer lastModifiedBy; 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/SecurityApplication.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security; 2 | 3 | import com.alibou.security.auth.AuthenticationService; 4 | import com.alibou.security.auth.RegisterRequest; 5 | import com.alibou.security.user.Role; 6 | import org.springframework.boot.CommandLineRunner; 7 | import org.springframework.boot.SpringApplication; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | import org.springframework.context.annotation.Bean; 10 | import org.springframework.data.jpa.repository.config.EnableJpaAuditing; 11 | 12 | import static com.alibou.security.user.Role.ADMIN; 13 | import static com.alibou.security.user.Role.MANAGER; 14 | 15 | @SpringBootApplication 16 | @EnableJpaAuditing(auditorAwareRef = "auditorAware") 17 | public class SecurityApplication { 18 | 19 | public static void main(String[] args) { 20 | SpringApplication.run(SecurityApplication.class, args); 21 | } 22 | 23 | @Bean 24 | public CommandLineRunner commandLineRunner( 25 | AuthenticationService service 26 | ) { 27 | return args -> { 28 | var admin = RegisterRequest.builder() 29 | .firstname("Admin") 30 | .lastname("Admin") 31 | .email("admin@mail.com") 32 | .password("password") 33 | .role(ADMIN) 34 | .build(); 35 | System.out.println("Admin token: " + service.register(admin).getAccessToken()); 36 | 37 | var manager = RegisterRequest.builder() 38 | .firstname("Admin") 39 | .lastname("Admin") 40 | .email("manager@mail.com") 41 | .password("password") 42 | .role(MANAGER) 43 | .build(); 44 | System.out.println("Manager token: " + service.register(manager).getAccessToken()); 45 | 46 | }; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/demo/ManagementController.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.demo; 2 | 3 | import io.swagger.v3.oas.annotations.Operation; 4 | import io.swagger.v3.oas.annotations.responses.ApiResponse; 5 | import io.swagger.v3.oas.annotations.tags.Tag; 6 | import org.springframework.web.bind.annotation.DeleteMapping; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.PostMapping; 9 | import org.springframework.web.bind.annotation.PutMapping; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | @RestController 14 | @RequestMapping("/api/v1/management") 15 | @Tag(name = "Management") 16 | public class ManagementController { 17 | 18 | 19 | @Operation( 20 | description = "Get endpoint for manager", 21 | summary = "This is a summary for management get endpoint", 22 | responses = { 23 | @ApiResponse( 24 | description = "Success", 25 | responseCode = "200" 26 | ), 27 | @ApiResponse( 28 | description = "Unauthorized / Invalid Token", 29 | responseCode = "403" 30 | ) 31 | } 32 | 33 | ) 34 | @GetMapping 35 | public String get() { 36 | return "GET:: management controller"; 37 | } 38 | @PostMapping 39 | public String post() { 40 | return "POST:: management controller"; 41 | } 42 | @PutMapping 43 | public String put() { 44 | return "PUT:: management controller"; 45 | } 46 | @DeleteMapping 47 | public String delete() { 48 | return "DELETE:: management controller"; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/user/User.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.user; 2 | 3 | import com.alibou.security.token.Token; 4 | import jakarta.persistence.Entity; 5 | import jakarta.persistence.EnumType; 6 | import jakarta.persistence.Enumerated; 7 | import jakarta.persistence.GeneratedValue; 8 | import jakarta.persistence.Id; 9 | import jakarta.persistence.OneToMany; 10 | import jakarta.persistence.Table; 11 | import java.util.Collection; 12 | import java.util.List; 13 | import lombok.AllArgsConstructor; 14 | import lombok.Builder; 15 | import lombok.Data; 16 | import lombok.NoArgsConstructor; 17 | import org.springframework.security.core.GrantedAuthority; 18 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 19 | import org.springframework.security.core.userdetails.UserDetails; 20 | 21 | @Data 22 | @Builder 23 | @NoArgsConstructor 24 | @AllArgsConstructor 25 | @Entity 26 | @Table(name = "_user") 27 | public class User implements UserDetails { 28 | 29 | @Id 30 | @GeneratedValue 31 | private Integer id; 32 | private String firstname; 33 | private String lastname; 34 | private String email; 35 | private String password; 36 | 37 | @Enumerated(EnumType.STRING) 38 | private Role role; 39 | 40 | @OneToMany(mappedBy = "user") 41 | private List tokens; 42 | 43 | @Override 44 | public Collection getAuthorities() { 45 | return role.getAuthorities(); 46 | } 47 | 48 | @Override 49 | public String getPassword() { 50 | return password; 51 | } 52 | 53 | @Override 54 | public String getUsername() { 55 | return email; 56 | } 57 | 58 | @Override 59 | public boolean isAccountNonExpired() { 60 | return true; 61 | } 62 | 63 | @Override 64 | public boolean isAccountNonLocked() { 65 | return true; 66 | } 67 | 68 | @Override 69 | public boolean isCredentialsNonExpired() { 70 | return true; 71 | } 72 | 73 | @Override 74 | public boolean isEnabled() { 75 | return true; 76 | } 77 | } 78 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/user/Role.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.user; 2 | 3 | import lombok.Getter; 4 | import lombok.RequiredArgsConstructor; 5 | import org.springframework.security.core.authority.SimpleGrantedAuthority; 6 | 7 | import java.util.Collections; 8 | import java.util.List; 9 | import java.util.Set; 10 | import java.util.stream.Collectors; 11 | 12 | import static com.alibou.security.user.Permission.ADMIN_CREATE; 13 | import static com.alibou.security.user.Permission.ADMIN_DELETE; 14 | import static com.alibou.security.user.Permission.ADMIN_READ; 15 | import static com.alibou.security.user.Permission.ADMIN_UPDATE; 16 | import static com.alibou.security.user.Permission.MANAGER_CREATE; 17 | import static com.alibou.security.user.Permission.MANAGER_DELETE; 18 | import static com.alibou.security.user.Permission.MANAGER_READ; 19 | import static com.alibou.security.user.Permission.MANAGER_UPDATE; 20 | 21 | @RequiredArgsConstructor 22 | public enum Role { 23 | 24 | USER(Collections.emptySet()), 25 | ADMIN( 26 | Set.of( 27 | ADMIN_READ, 28 | ADMIN_UPDATE, 29 | ADMIN_DELETE, 30 | ADMIN_CREATE, 31 | MANAGER_READ, 32 | MANAGER_UPDATE, 33 | MANAGER_DELETE, 34 | MANAGER_CREATE 35 | ) 36 | ), 37 | MANAGER( 38 | Set.of( 39 | MANAGER_READ, 40 | MANAGER_UPDATE, 41 | MANAGER_DELETE, 42 | MANAGER_CREATE 43 | ) 44 | ) 45 | 46 | ; 47 | 48 | @Getter 49 | private final Set permissions; 50 | 51 | public List getAuthorities() { 52 | var authorities = getPermissions() 53 | .stream() 54 | .map(permission -> new SimpleGrantedAuthority(permission.getPermission())) 55 | .collect(Collectors.toList()); 56 | authorities.add(new SimpleGrantedAuthority("ROLE_" + this.name())); 57 | return authorities; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/config/OpenApiConfig.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.config; 2 | 3 | import io.swagger.v3.oas.annotations.OpenAPIDefinition; 4 | import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn; 5 | import io.swagger.v3.oas.annotations.enums.SecuritySchemeType; 6 | import io.swagger.v3.oas.annotations.info.Contact; 7 | import io.swagger.v3.oas.annotations.info.Info; 8 | import io.swagger.v3.oas.annotations.info.License; 9 | import io.swagger.v3.oas.annotations.security.SecurityRequirement; 10 | import io.swagger.v3.oas.annotations.security.SecurityScheme; 11 | import io.swagger.v3.oas.annotations.servers.Server; 12 | 13 | @OpenAPIDefinition( 14 | info = @Info( 15 | contact = @Contact( 16 | name = "Alibou", 17 | email = "contact@aliboucoding.com", 18 | url = "https://aliboucoding.com/course" 19 | ), 20 | description = "OpenApi documentation for Spring Security", 21 | title = "OpenApi specification - Alibou", 22 | version = "1.0", 23 | license = @License( 24 | name = "Licence name", 25 | url = "https://some-url.com" 26 | ), 27 | termsOfService = "Terms of service" 28 | ), 29 | servers = { 30 | @Server( 31 | description = "Local ENV", 32 | url = "http://localhost:8080" 33 | ), 34 | @Server( 35 | description = "PROD ENV", 36 | url = "https://aliboucoding.com/course" 37 | ) 38 | }, 39 | security = { 40 | @SecurityRequirement( 41 | name = "bearerAuth" 42 | ) 43 | } 44 | ) 45 | @SecurityScheme( 46 | name = "bearerAuth", 47 | description = "JWT auth description", 48 | scheme = "bearer", 49 | type = SecuritySchemeType.HTTP, 50 | bearerFormat = "JWT", 51 | in = SecuritySchemeIn.HEADER 52 | ) 53 | public class OpenApiConfig { 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/config/ApplicationConfig.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.config; 2 | 3 | import com.alibou.security.auditing.ApplicationAuditAware; 4 | import com.alibou.security.user.UserRepository; 5 | import jakarta.persistence.criteria.CriteriaBuilder; 6 | import lombok.RequiredArgsConstructor; 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.data.domain.AuditorAware; 10 | import org.springframework.security.authentication.AuthenticationManager; 11 | import org.springframework.security.authentication.AuthenticationProvider; 12 | import org.springframework.security.authentication.dao.DaoAuthenticationProvider; 13 | import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; 14 | import org.springframework.security.core.userdetails.UserDetailsService; 15 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 16 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 17 | import org.springframework.security.crypto.password.PasswordEncoder; 18 | 19 | @Configuration 20 | @RequiredArgsConstructor 21 | public class ApplicationConfig { 22 | 23 | private final UserRepository repository; 24 | 25 | @Bean 26 | public UserDetailsService userDetailsService() { 27 | return username -> repository.findByEmail(username) 28 | .orElseThrow(() -> new UsernameNotFoundException("User not found")); 29 | } 30 | 31 | @Bean 32 | public AuthenticationProvider authenticationProvider() { 33 | DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); 34 | authProvider.setUserDetailsService(userDetailsService()); 35 | authProvider.setPasswordEncoder(passwordEncoder()); 36 | return authProvider; 37 | } 38 | 39 | @Bean 40 | public AuditorAware auditorAware() { 41 | return new ApplicationAuditAware(); 42 | } 43 | 44 | @Bean 45 | public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception { 46 | return config.getAuthenticationManager(); 47 | } 48 | 49 | @Bean 50 | public PasswordEncoder passwordEncoder() { 51 | return new BCryptPasswordEncoder(); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/config/JwtAuthenticationFilter.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.config; 2 | 3 | import com.alibou.security.token.TokenRepository; 4 | import jakarta.servlet.FilterChain; 5 | import jakarta.servlet.ServletException; 6 | import jakarta.servlet.http.HttpServletRequest; 7 | import jakarta.servlet.http.HttpServletResponse; 8 | 9 | import java.beans.Transient; 10 | import java.io.IOException; 11 | import java.security.Security; 12 | 13 | import jakarta.transaction.TransactionScoped; 14 | import jakarta.transaction.Transactional; 15 | import lombok.RequiredArgsConstructor; 16 | import org.springframework.lang.NonNull; 17 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 18 | import org.springframework.security.core.context.SecurityContextHolder; 19 | import org.springframework.security.core.userdetails.UserDetails; 20 | import org.springframework.security.core.userdetails.UserDetailsService; 21 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 22 | import org.springframework.stereotype.Component; 23 | import org.springframework.web.filter.OncePerRequestFilter; 24 | 25 | @Component 26 | @RequiredArgsConstructor 27 | public class JwtAuthenticationFilter extends OncePerRequestFilter { 28 | 29 | private final JwtService jwtService; 30 | private final UserDetailsService userDetailsService; 31 | private final TokenRepository tokenRepository; 32 | 33 | @Override 34 | protected void doFilterInternal( 35 | @NonNull HttpServletRequest request, 36 | @NonNull HttpServletResponse response, 37 | @NonNull FilterChain filterChain 38 | ) throws ServletException, IOException { 39 | if (request.getServletPath().contains("/api/v1/auth")) { 40 | filterChain.doFilter(request, response); 41 | return; 42 | } 43 | final String authHeader = request.getHeader("Authorization"); 44 | final String jwt; 45 | final String userEmail; 46 | if (authHeader == null ||!authHeader.startsWith("Bearer ")) { 47 | filterChain.doFilter(request, response); 48 | return; 49 | } 50 | jwt = authHeader.substring(7); 51 | userEmail = jwtService.extractUsername(jwt); 52 | if (userEmail != null && SecurityContextHolder.getContext().getAuthentication() == null) { 53 | UserDetails userDetails = this.userDetailsService.loadUserByUsername(userEmail); 54 | var isTokenValid = tokenRepository.findByToken(jwt) 55 | .map(t -> !t.isExpired() && !t.isRevoked()) 56 | .orElse(false); 57 | if (jwtService.isTokenValid(jwt, userDetails) && isTokenValid) { 58 | UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken( 59 | userDetails, 60 | null, 61 | userDetails.getAuthorities() 62 | ); 63 | authToken.setDetails( 64 | new WebAuthenticationDetailsSource().buildDetails(request) 65 | ); 66 | SecurityContextHolder.getContext().setAuthentication(authToken); 67 | } 68 | } 69 | filterChain.doFilter(request, response); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 3.1.4 9 | 10 | 11 | com.alibou 12 | security 13 | 0.0.1-SNAPSHOT 14 | security 15 | Demo project for Spring Boot 16 | 17 | 17 18 | 19 | 20 | 21 | org.springframework.boot 22 | spring-boot-starter-data-jpa 23 | 24 | 25 | org.springframework.boot 26 | spring-boot-starter-security 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-web 31 | 32 | 33 | 34 | org.postgresql 35 | postgresql 36 | runtime 37 | 38 | 39 | org.projectlombok 40 | lombok 41 | true 42 | 43 | 44 | io.jsonwebtoken 45 | jjwt-api 46 | 0.11.5 47 | 48 | 49 | io.jsonwebtoken 50 | jjwt-impl 51 | 0.11.5 52 | 53 | 54 | io.jsonwebtoken 55 | jjwt-jackson 56 | 0.11.5 57 | 58 | 59 | org.springdoc 60 | springdoc-openapi-starter-webmvc-ui 61 | 2.1.0 62 | 63 | 64 | org.springframework.boot 65 | spring-boot-starter-validation 66 | 67 | 68 | 69 | org.springframework.boot 70 | spring-boot-starter-test 71 | test 72 | 73 | 74 | org.springframework.security 75 | spring-security-test 76 | test 77 | 78 | 79 | 80 | 81 | 82 | 83 | org.springframework.boot 84 | spring-boot-maven-plugin 85 | 86 | 87 | 88 | org.projectlombok 89 | lombok 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/config/JwtService.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.config; 2 | 3 | import io.jsonwebtoken.Claims; 4 | import io.jsonwebtoken.Jwts; 5 | import io.jsonwebtoken.SignatureAlgorithm; 6 | import io.jsonwebtoken.io.Decoders; 7 | import io.jsonwebtoken.security.Keys; 8 | import java.security.Key; 9 | import java.util.Date; 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | import java.util.function.Function; 13 | 14 | import org.springframework.beans.factory.annotation.Value; 15 | import org.springframework.security.core.userdetails.UserDetails; 16 | import org.springframework.stereotype.Service; 17 | 18 | @Service 19 | public class JwtService { 20 | 21 | @Value("${application.security.jwt.secret-key}") 22 | private String secretKey; 23 | @Value("${application.security.jwt.expiration}") 24 | private long jwtExpiration; 25 | @Value("${application.security.jwt.refresh-token.expiration}") 26 | private long refreshExpiration; 27 | 28 | public String extractUsername(String token) { 29 | return extractClaim(token, Claims::getSubject); 30 | } 31 | 32 | public T extractClaim(String token, Function claimsResolver) { 33 | final Claims claims = extractAllClaims(token); 34 | return claimsResolver.apply(claims); 35 | } 36 | 37 | public String generateToken(UserDetails userDetails) { 38 | return generateToken(new HashMap<>(), userDetails); 39 | } 40 | 41 | public String generateToken( 42 | Map extraClaims, 43 | UserDetails userDetails 44 | ) { 45 | return buildToken(extraClaims, userDetails, jwtExpiration); 46 | } 47 | 48 | public String generateRefreshToken( 49 | UserDetails userDetails 50 | ) { 51 | return buildToken(new HashMap<>(), userDetails, refreshExpiration); 52 | } 53 | 54 | private String buildToken( 55 | Map extraClaims, 56 | UserDetails userDetails, 57 | long expiration 58 | ) { 59 | return Jwts 60 | .builder() 61 | .setClaims(extraClaims) 62 | .setSubject(userDetails.getUsername()) 63 | .setIssuedAt(new Date(System.currentTimeMillis())) 64 | .setExpiration(new Date(System.currentTimeMillis() + expiration)) 65 | .signWith(getSignInKey(), SignatureAlgorithm.HS256) 66 | .compact(); 67 | } 68 | 69 | public boolean isTokenValid(String token, UserDetails userDetails) { 70 | final String username = extractUsername(token); 71 | return (username.equals(userDetails.getUsername())) && !isTokenExpired(token); 72 | } 73 | 74 | private boolean isTokenExpired(String token) { 75 | return extractExpiration(token).before(new Date()); 76 | } 77 | 78 | private Date extractExpiration(String token) { 79 | return extractClaim(token, Claims::getExpiration); 80 | } 81 | 82 | private Claims extractAllClaims(String token) { 83 | return Jwts 84 | .parserBuilder() 85 | .setSigningKey(getSignInKey()) 86 | .build() 87 | .parseClaimsJws(token) 88 | .getBody(); 89 | } 90 | 91 | private Key getSignInKey() { 92 | byte[] keyBytes = Decoders.BASE64.decode(secretKey); 93 | return Keys.hmacShaKeyFor(keyBytes); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/config/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.config; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.security.authentication.AuthenticationProvider; 7 | import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; 8 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 9 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 10 | import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; 11 | import org.springframework.security.core.context.SecurityContextHolder; 12 | import org.springframework.security.web.SecurityFilterChain; 13 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 14 | import org.springframework.security.web.authentication.logout.LogoutHandler; 15 | 16 | import static com.alibou.security.user.Permission.ADMIN_CREATE; 17 | import static com.alibou.security.user.Permission.ADMIN_DELETE; 18 | import static com.alibou.security.user.Permission.ADMIN_READ; 19 | import static com.alibou.security.user.Permission.ADMIN_UPDATE; 20 | import static com.alibou.security.user.Permission.MANAGER_CREATE; 21 | import static com.alibou.security.user.Permission.MANAGER_DELETE; 22 | import static com.alibou.security.user.Permission.MANAGER_READ; 23 | import static com.alibou.security.user.Permission.MANAGER_UPDATE; 24 | import static com.alibou.security.user.Role.ADMIN; 25 | import static com.alibou.security.user.Role.MANAGER; 26 | import static org.springframework.http.HttpMethod.DELETE; 27 | import static org.springframework.http.HttpMethod.GET; 28 | import static org.springframework.http.HttpMethod.POST; 29 | import static org.springframework.http.HttpMethod.PUT; 30 | import static org.springframework.security.config.http.SessionCreationPolicy.STATELESS; 31 | 32 | @Configuration 33 | @EnableWebSecurity 34 | @RequiredArgsConstructor 35 | @EnableMethodSecurity 36 | public class SecurityConfiguration { 37 | 38 | private static final String[] WHITE_LIST_URL = {"/api/v1/auth/**", 39 | "/v2/api-docs", 40 | "/v3/api-docs", 41 | "/v3/api-docs/**", 42 | "/swagger-resources", 43 | "/swagger-resources/**", 44 | "/configuration/ui", 45 | "/configuration/security", 46 | "/swagger-ui/**", 47 | "/webjars/**", 48 | "/swagger-ui.html"}; 49 | private final JwtAuthenticationFilter jwtAuthFilter; 50 | private final AuthenticationProvider authenticationProvider; 51 | private final LogoutHandler logoutHandler; 52 | 53 | @Bean 54 | public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 55 | http 56 | .csrf(AbstractHttpConfigurer::disable) 57 | .authorizeHttpRequests(req -> 58 | req.requestMatchers(WHITE_LIST_URL) 59 | .permitAll() 60 | .requestMatchers("/api/v1/management/**").hasAnyRole(ADMIN.name(), MANAGER.name()) 61 | .requestMatchers(GET, "/api/v1/management/**").hasAnyAuthority(ADMIN_READ.name(), MANAGER_READ.name()) 62 | .requestMatchers(POST, "/api/v1/management/**").hasAnyAuthority(ADMIN_CREATE.name(), MANAGER_CREATE.name()) 63 | .requestMatchers(PUT, "/api/v1/management/**").hasAnyAuthority(ADMIN_UPDATE.name(), MANAGER_UPDATE.name()) 64 | .requestMatchers(DELETE, "/api/v1/management/**").hasAnyAuthority(ADMIN_DELETE.name(), MANAGER_DELETE.name()) 65 | .anyRequest() 66 | .authenticated() 67 | ) 68 | .sessionManagement(session -> session.sessionCreationPolicy(STATELESS)) 69 | .authenticationProvider(authenticationProvider) 70 | .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) 71 | .logout(logout -> 72 | logout.logoutUrl("/api/v1/auth/logout") 73 | .addLogoutHandler(logoutHandler) 74 | .logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext()) 75 | ) 76 | ; 77 | 78 | return http.build(); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/com/alibou/security/auth/AuthenticationService.java: -------------------------------------------------------------------------------- 1 | package com.alibou.security.auth; 2 | 3 | import com.alibou.security.config.JwtService; 4 | import com.alibou.security.token.Token; 5 | import com.alibou.security.token.TokenRepository; 6 | import com.alibou.security.token.TokenType; 7 | import com.alibou.security.user.Role; 8 | import com.alibou.security.user.User; 9 | import com.alibou.security.user.UserRepository; 10 | import com.fasterxml.jackson.databind.ObjectMapper; 11 | import jakarta.servlet.http.HttpServletRequest; 12 | import jakarta.servlet.http.HttpServletResponse; 13 | import lombok.RequiredArgsConstructor; 14 | import org.springframework.http.HttpHeaders; 15 | import org.springframework.security.authentication.AuthenticationManager; 16 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 17 | import org.springframework.security.core.context.SecurityContextHolder; 18 | import org.springframework.security.core.userdetails.UserDetails; 19 | import org.springframework.security.crypto.password.PasswordEncoder; 20 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 21 | import org.springframework.stereotype.Service; 22 | 23 | import java.io.IOException; 24 | 25 | @Service 26 | @RequiredArgsConstructor 27 | public class AuthenticationService { 28 | private final UserRepository repository; 29 | private final TokenRepository tokenRepository; 30 | private final PasswordEncoder passwordEncoder; 31 | private final JwtService jwtService; 32 | private final AuthenticationManager authenticationManager; 33 | 34 | public AuthenticationResponse register(RegisterRequest request) { 35 | var user = User.builder() 36 | .firstname(request.getFirstname()) 37 | .lastname(request.getLastname()) 38 | .email(request.getEmail()) 39 | .password(passwordEncoder.encode(request.getPassword())) 40 | .role(request.getRole()) 41 | .build(); 42 | var savedUser = repository.save(user); 43 | var jwtToken = jwtService.generateToken(user); 44 | var refreshToken = jwtService.generateRefreshToken(user); 45 | saveUserToken(savedUser, jwtToken); 46 | return AuthenticationResponse.builder() 47 | .accessToken(jwtToken) 48 | .refreshToken(refreshToken) 49 | .build(); 50 | } 51 | 52 | public AuthenticationResponse authenticate(AuthenticationRequest request) { 53 | authenticationManager.authenticate( 54 | new UsernamePasswordAuthenticationToken( 55 | request.getEmail(), 56 | request.getPassword() 57 | ) 58 | ); 59 | var user = repository.findByEmail(request.getEmail()) 60 | .orElseThrow(); 61 | var jwtToken = jwtService.generateToken(user); 62 | var refreshToken = jwtService.generateRefreshToken(user); 63 | revokeAllUserTokens(user); 64 | saveUserToken(user, jwtToken); 65 | return AuthenticationResponse.builder() 66 | .accessToken(jwtToken) 67 | .refreshToken(refreshToken) 68 | .build(); 69 | } 70 | 71 | private void saveUserToken(User user, String jwtToken) { 72 | var token = Token.builder() 73 | .user(user) 74 | .token(jwtToken) 75 | .tokenType(TokenType.BEARER) 76 | .expired(false) 77 | .revoked(false) 78 | .build(); 79 | tokenRepository.save(token); 80 | } 81 | 82 | private void revokeAllUserTokens(User user) { 83 | var validUserTokens = tokenRepository.findAllValidTokenByUser(user.getId()); 84 | if (validUserTokens.isEmpty()) 85 | return; 86 | validUserTokens.forEach(token -> { 87 | token.setExpired(true); 88 | token.setRevoked(true); 89 | }); 90 | tokenRepository.saveAll(validUserTokens); 91 | } 92 | 93 | public void refreshToken( 94 | HttpServletRequest request, 95 | HttpServletResponse response 96 | ) throws IOException { 97 | final String authHeader = request.getHeader(HttpHeaders.AUTHORIZATION); 98 | final String refreshToken; 99 | final String userEmail; 100 | if (authHeader == null ||!authHeader.startsWith("Bearer ")) { 101 | return; 102 | } 103 | refreshToken = authHeader.substring(7); 104 | userEmail = jwtService.extractUsername(refreshToken); 105 | if (userEmail != null) { 106 | var user = this.repository.findByEmail(userEmail) 107 | .orElseThrow(); 108 | if (jwtService.isTokenValid(refreshToken, user)) { 109 | var accessToken = jwtService.generateToken(user); 110 | revokeAllUserTokens(user); 111 | saveUserToken(user, accessToken); 112 | var authResponse = AuthenticationResponse.builder() 113 | .accessToken(accessToken) 114 | .refreshToken(refreshToken) 115 | .build(); 116 | new ObjectMapper().writeValue(response.getOutputStream(), authResponse); 117 | } 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 50 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 124 | 125 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% ^ 162 | %JVM_CONFIG_MAVEN_PROPS% ^ 163 | %MAVEN_OPTS% ^ 164 | %MAVEN_DEBUG_OPTS% ^ 165 | -classpath %WRAPPER_JAR% ^ 166 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 167 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 168 | if ERRORLEVEL 1 goto error 169 | goto end 170 | 171 | :error 172 | set ERROR_CODE=1 173 | 174 | :end 175 | @endlocal & set ERROR_CODE=%ERROR_CODE% 176 | 177 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 178 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 179 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 180 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 181 | :skipRcPost 182 | 183 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 184 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 185 | 186 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 187 | 188 | cmd /C exit /B %ERROR_CODE% 189 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # https://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /usr/local/etc/mavenrc ] ; then 40 | . /usr/local/etc/mavenrc 41 | fi 42 | 43 | if [ -f /etc/mavenrc ] ; then 44 | . /etc/mavenrc 45 | fi 46 | 47 | if [ -f "$HOME/.mavenrc" ] ; then 48 | . "$HOME/.mavenrc" 49 | fi 50 | 51 | fi 52 | 53 | # OS specific support. $var _must_ be set to either true or false. 54 | cygwin=false; 55 | darwin=false; 56 | mingw=false 57 | case "`uname`" in 58 | CYGWIN*) cygwin=true ;; 59 | MINGW*) mingw=true;; 60 | Darwin*) darwin=true 61 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 62 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 63 | if [ -z "$JAVA_HOME" ]; then 64 | if [ -x "/usr/libexec/java_home" ]; then 65 | export JAVA_HOME="`/usr/libexec/java_home`" 66 | else 67 | export JAVA_HOME="/Library/Java/Home" 68 | fi 69 | fi 70 | ;; 71 | esac 72 | 73 | if [ -z "$JAVA_HOME" ] ; then 74 | if [ -r /etc/gentoo-release ] ; then 75 | JAVA_HOME=`java-config --jre-home` 76 | fi 77 | fi 78 | 79 | if [ -z "$M2_HOME" ] ; then 80 | ## resolve links - $0 may be a link to maven's home 81 | PRG="$0" 82 | 83 | # need this for relative symlinks 84 | while [ -h "$PRG" ] ; do 85 | ls=`ls -ld "$PRG"` 86 | link=`expr "$ls" : '.*-> \(.*\)$'` 87 | if expr "$link" : '/.*' > /dev/null; then 88 | PRG="$link" 89 | else 90 | PRG="`dirname "$PRG"`/$link" 91 | fi 92 | done 93 | 94 | saveddir=`pwd` 95 | 96 | M2_HOME=`dirname "$PRG"`/.. 97 | 98 | # make it fully qualified 99 | M2_HOME=`cd "$M2_HOME" && pwd` 100 | 101 | cd "$saveddir" 102 | # echo Using m2 at $M2_HOME 103 | fi 104 | 105 | # For Cygwin, ensure paths are in UNIX format before anything is touched 106 | if $cygwin ; then 107 | [ -n "$M2_HOME" ] && 108 | M2_HOME=`cygpath --unix "$M2_HOME"` 109 | [ -n "$JAVA_HOME" ] && 110 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 111 | [ -n "$CLASSPATH" ] && 112 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 113 | fi 114 | 115 | # For Mingw, ensure paths are in UNIX format before anything is touched 116 | if $mingw ; then 117 | [ -n "$M2_HOME" ] && 118 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 119 | [ -n "$JAVA_HOME" ] && 120 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 121 | fi 122 | 123 | if [ -z "$JAVA_HOME" ]; then 124 | javaExecutable="`which javac`" 125 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 126 | # readlink(1) is not available as standard on Solaris 10. 127 | readLink=`which readlink` 128 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 129 | if $darwin ; then 130 | javaHome="`dirname \"$javaExecutable\"`" 131 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 132 | else 133 | javaExecutable="`readlink -f \"$javaExecutable\"`" 134 | fi 135 | javaHome="`dirname \"$javaExecutable\"`" 136 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 137 | JAVA_HOME="$javaHome" 138 | export JAVA_HOME 139 | fi 140 | fi 141 | fi 142 | 143 | if [ -z "$JAVACMD" ] ; then 144 | if [ -n "$JAVA_HOME" ] ; then 145 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 146 | # IBM's JDK on AIX uses strange locations for the executables 147 | JAVACMD="$JAVA_HOME/jre/sh/java" 148 | else 149 | JAVACMD="$JAVA_HOME/bin/java" 150 | fi 151 | else 152 | JAVACMD="`\\unset -f command; \\command -v java`" 153 | fi 154 | fi 155 | 156 | if [ ! -x "$JAVACMD" ] ; then 157 | echo "Error: JAVA_HOME is not defined correctly." >&2 158 | echo " We cannot execute $JAVACMD" >&2 159 | exit 1 160 | fi 161 | 162 | if [ -z "$JAVA_HOME" ] ; then 163 | echo "Warning: JAVA_HOME environment variable is not set." 164 | fi 165 | 166 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 167 | 168 | # traverses directory structure from process work directory to filesystem root 169 | # first directory with .mvn subdirectory is considered project base directory 170 | find_maven_basedir() { 171 | 172 | if [ -z "$1" ] 173 | then 174 | echo "Path not specified to find_maven_basedir" 175 | return 1 176 | fi 177 | 178 | basedir="$1" 179 | wdir="$1" 180 | while [ "$wdir" != '/' ] ; do 181 | if [ -d "$wdir"/.mvn ] ; then 182 | basedir=$wdir 183 | break 184 | fi 185 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 186 | if [ -d "${wdir}" ]; then 187 | wdir=`cd "$wdir/.."; pwd` 188 | fi 189 | # end of workaround 190 | done 191 | echo "${basedir}" 192 | } 193 | 194 | # concatenates all lines of a file 195 | concat_lines() { 196 | if [ -f "$1" ]; then 197 | echo "$(tr -s '\n' ' ' < "$1")" 198 | fi 199 | } 200 | 201 | BASE_DIR=`find_maven_basedir "$(pwd)"` 202 | if [ -z "$BASE_DIR" ]; then 203 | exit 1; 204 | fi 205 | 206 | ########################################################################################## 207 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 208 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 209 | ########################################################################################## 210 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Found .mvn/wrapper/maven-wrapper.jar" 213 | fi 214 | else 215 | if [ "$MVNW_VERBOSE" = true ]; then 216 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 217 | fi 218 | if [ -n "$MVNW_REPOURL" ]; then 219 | jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 220 | else 221 | jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.0/maven-wrapper-3.1.0.jar" 222 | fi 223 | while IFS="=" read key value; do 224 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 225 | esac 226 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 227 | if [ "$MVNW_VERBOSE" = true ]; then 228 | echo "Downloading from: $jarUrl" 229 | fi 230 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 231 | if $cygwin; then 232 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 233 | fi 234 | 235 | if command -v wget > /dev/null; then 236 | if [ "$MVNW_VERBOSE" = true ]; then 237 | echo "Found wget ... using wget" 238 | fi 239 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 240 | wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 241 | else 242 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 243 | fi 244 | elif command -v curl > /dev/null; then 245 | if [ "$MVNW_VERBOSE" = true ]; then 246 | echo "Found curl ... using curl" 247 | fi 248 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 249 | curl -o "$wrapperJarPath" "$jarUrl" -f 250 | else 251 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 252 | fi 253 | 254 | else 255 | if [ "$MVNW_VERBOSE" = true ]; then 256 | echo "Falling back to using Java to download" 257 | fi 258 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 259 | # For Cygwin, switch paths to Windows format before running javac 260 | if $cygwin; then 261 | javaClass=`cygpath --path --windows "$javaClass"` 262 | fi 263 | if [ -e "$javaClass" ]; then 264 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 265 | if [ "$MVNW_VERBOSE" = true ]; then 266 | echo " - Compiling MavenWrapperDownloader.java ..." 267 | fi 268 | # Compiling the Java class 269 | ("$JAVA_HOME/bin/javac" "$javaClass") 270 | fi 271 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 272 | # Running the downloader 273 | if [ "$MVNW_VERBOSE" = true ]; then 274 | echo " - Running MavenWrapperDownloader.java ..." 275 | fi 276 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 277 | fi 278 | fi 279 | fi 280 | fi 281 | ########################################################################################## 282 | # End of extension 283 | ########################################################################################## 284 | 285 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 286 | if [ "$MVNW_VERBOSE" = true ]; then 287 | echo $MAVEN_PROJECTBASEDIR 288 | fi 289 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 290 | 291 | # For Cygwin, switch paths to Windows format before running java 292 | if $cygwin; then 293 | [ -n "$M2_HOME" ] && 294 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 295 | [ -n "$JAVA_HOME" ] && 296 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 297 | [ -n "$CLASSPATH" ] && 298 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 299 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 300 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 301 | fi 302 | 303 | # Provide a "standardized" way to retrieve the CLI args that will 304 | # work with both Windows and non-Windows executions. 305 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 306 | export MAVEN_CMD_LINE_ARGS 307 | 308 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 309 | 310 | exec "$JAVACMD" \ 311 | $MAVEN_OPTS \ 312 | $MAVEN_DEBUG_OPTS \ 313 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 314 | "-Dmaven.home=${M2_HOME}" \ 315 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 316 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 317 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /jwt-security.drawio: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | --------------------------------------------------------------------------------