├── scripts ├── start-services.sh ├── stop-services.sh ├── create-database.sh └── docker-compose.yaml ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── authentication-sequence-diagram.png ├── src ├── test │ ├── resources │ │ └── application-test.yml │ └── java │ │ └── com │ │ └── mina │ │ └── authentication │ │ └── controller │ │ └── AuthControllerIntegrationTest.java └── main │ ├── java │ └── com │ │ └── mina │ │ └── authentication │ │ ├── domain │ │ ├── User.java │ │ └── LoginAttempt.java │ │ ├── exceptions │ │ ├── NotFoundException.java │ │ ├── DuplicateException.java │ │ └── AccessDeniedException.java │ │ ├── controller │ │ ├── dto │ │ │ ├── LoginResponse.java │ │ │ ├── ApiErrorResponse.java │ │ │ ├── LoginAttemptResponse.java │ │ │ ├── LoginRequest.java │ │ │ └── SignupRequest.java │ │ ├── RestExceptionHandler.java │ │ └── AuthController.java │ │ ├── Main.java │ │ ├── service │ │ ├── LoginService.java │ │ ├── UserDetailsServiceImpl.java │ │ └── UserService.java │ │ ├── repository │ │ ├── UserRepository.java │ │ └── LoginAttemptRepository.java │ │ ├── config │ │ ├── SwaggerConfiguration.java │ │ ├── JwtAuthFilter.java │ │ └── SecurityConfig.java │ │ └── helper │ │ └── JwtHelper.java │ └── resources │ ├── db │ ├── changelogs │ │ ├── 0_schema.xml │ │ └── 1_tables.xml │ └── changelog-master.xml │ └── application.yml ├── .gitignore ├── authentication.postman_collection.json ├── pom.xml ├── README.md ├── mvnw.cmd └── mvnw /scripts/start-services.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | echo "Starting dependencies" 4 | docker-compose up -d -------------------------------------------------------------------------------- /scripts/stop-services.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | echo "Stopping dependencies" 4 | docker-compose down -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/minarashidi/authentication/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /authentication-sequence-diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/minarashidi/authentication/HEAD/authentication-sequence-diagram.png -------------------------------------------------------------------------------- /src/test/resources/application-test.yml: -------------------------------------------------------------------------------- 1 | server: 2 | shutdown: immediate 3 | 4 | spring.liquibase.enabled: true 5 | 6 | logging.level: 7 | root: INFO 8 | liquibase: INFO -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/domain/User.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.domain; 2 | 3 | public record User(String name, 4 | String email, 5 | String password) { 6 | 7 | } 8 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.5/apache-maven-3.9.5-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar 3 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/exceptions/NotFoundException.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.exceptions; 2 | 3 | public class NotFoundException extends RuntimeException { 4 | 5 | public NotFoundException(String message) { 6 | super(message); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/exceptions/DuplicateException.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.exceptions; 2 | 3 | public class DuplicateException extends RuntimeException { 4 | 5 | public DuplicateException(String message) { 6 | super(message); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/exceptions/AccessDeniedException.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.exceptions; 2 | 3 | public class AccessDeniedException extends RuntimeException { 4 | 5 | public AccessDeniedException(String message) { 6 | super(message); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/domain/LoginAttempt.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.domain; 2 | 3 | import java.time.LocalDateTime; 4 | 5 | public record LoginAttempt(String email, 6 | boolean success, 7 | LocalDateTime createdAt) { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/controller/dto/LoginResponse.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.controller.dto; 2 | 3 | import io.swagger.v3.oas.annotations.media.Schema; 4 | 5 | public record LoginResponse( 6 | @Schema(description = "email") 7 | String email, 8 | @Schema(description = "JWT token") 9 | String token) { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /scripts/create-database.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | DOCKER_CONTAINER=postgres 4 | PG_USER=postgres 5 | DATABASE=authentication 6 | 7 | echo "Removing ${DATABASE}" 8 | docker exec -i ${DOCKER_CONTAINER} dropdb ${DATABASE} --username=${PG_USER} 9 | 10 | echo "Creating ${DATABASE}" 11 | docker exec -i ${DOCKER_CONTAINER} createdb ${DATABASE} --username=${PG_USER} 12 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/controller/dto/ApiErrorResponse.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.controller.dto; 2 | 3 | import io.swagger.v3.oas.annotations.media.Schema; 4 | 5 | public record ApiErrorResponse( 6 | @Schema(description = "Error code") 7 | int errorCode, 8 | @Schema(description = "Error description") 9 | String description) { 10 | 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/Main.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class Main { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(Main.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /scripts/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | 3 | services: 4 | postgres: 5 | container_name: postgres 6 | image: postgres:13 7 | environment: 8 | POSTGRES_USER: ${POSTGRES_USER:-postgres} 9 | POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres} 10 | POSTGRES_DB: authentication 11 | POSTGRES_HOST_AUTH_METHOD: trust 12 | PGDATA: /data/postgres 13 | volumes: 14 | - ./postgres/data:/data/postgres 15 | ports: 16 | - "5432:5432" 17 | -------------------------------------------------------------------------------- /.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/resources/db/changelogs/0_schema.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | CREATE SCHEMA IF NOT EXISTS authentication; 9 | 10 | 11 | DROP SCHEMA IF EXISTS authentication; 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/main/resources/db/changelog-master.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/controller/dto/LoginAttemptResponse.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.controller.dto; 2 | 3 | import com.mina.authentication.domain.LoginAttempt; 4 | import io.swagger.v3.oas.annotations.media.Schema; 5 | import java.time.LocalDateTime; 6 | 7 | public record LoginAttemptResponse( 8 | @Schema(description = "The date and time of the login attempt") LocalDateTime createdAt, 9 | @Schema(description = "The login status") boolean success) { 10 | 11 | public static LoginAttemptResponse convertToDTO(LoginAttempt loginAttempt) { 12 | return new LoginAttemptResponse(loginAttempt.createdAt(), loginAttempt.success()); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/controller/dto/LoginRequest.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.controller.dto; 2 | 3 | import io.swagger.v3.oas.annotations.media.Schema; 4 | import jakarta.validation.constraints.Email; 5 | import jakarta.validation.constraints.NotBlank; 6 | import jakarta.validation.constraints.Size; 7 | 8 | public record LoginRequest( 9 | @Schema(description = "email", example = "mina@gmail.com") 10 | @NotBlank(message = "Email cannot be blank") 11 | @Email(message = "Invalid email format") 12 | String email, 13 | 14 | @Schema(description = "password", example = "123456") 15 | @NotBlank(message = "Password cannot be blank") 16 | @Size(min = 6, max = 20, message = "Password must be between 6 and 20 characters") 17 | String password) { 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/controller/dto/SignupRequest.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.controller.dto; 2 | 3 | import io.swagger.v3.oas.annotations.media.Schema; 4 | import jakarta.validation.constraints.Email; 5 | import jakarta.validation.constraints.NotBlank; 6 | import jakarta.validation.constraints.Size; 7 | 8 | public record SignupRequest( 9 | @Schema(description = "name", example = "Mina") 10 | @NotBlank(message = "Name cannot be blank") 11 | String name, 12 | 13 | @Schema(description = "email", example = "mina@gmail.com") 14 | @Email(message = "Invalid email format") 15 | @NotBlank(message = "Email cannot be blank") 16 | String email, 17 | 18 | @Schema(description = "password", example = "123456") 19 | @NotBlank(message = "Password cannot be blank") 20 | @Size(min = 6, max = 20, message = "Password must be between 6 and 20 characters") 21 | String password) { 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/service/LoginService.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.service; 2 | 3 | import com.mina.authentication.domain.LoginAttempt; 4 | import com.mina.authentication.repository.LoginAttemptRepository; 5 | import java.time.LocalDateTime; 6 | import java.util.List; 7 | import org.springframework.stereotype.Service; 8 | import org.springframework.transaction.annotation.Transactional; 9 | 10 | @Service 11 | @Transactional(readOnly = true) 12 | public class LoginService { 13 | 14 | private final LoginAttemptRepository repository; 15 | 16 | public LoginService(LoginAttemptRepository repository) { 17 | this.repository = repository; 18 | } 19 | 20 | @Transactional 21 | public void addLoginAttempt(String email, boolean success) { 22 | LoginAttempt loginAttempt = new LoginAttempt(email, success, LocalDateTime.now()); 23 | repository.add(loginAttempt); 24 | } 25 | 26 | public List findRecentLoginAttempts(String email) { 27 | return repository.findRecent(email); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8080 3 | # graceful shutdown makes sure we have time to finnish any ongoing rest requests before terminating 4 | # default value will be 30s before terminating 5 | shutdown: graceful 6 | 7 | spring: 8 | threads: 9 | virtual: 10 | enabled: true #To enable virtual threads in Spring Boot 3.2 we just need to set this property 11 | application: 12 | name: authentication 13 | datasource: 14 | url: jdbc:postgresql://localhost:5432/authentication?prepareThreshold=0 15 | driver-class-name: org.postgresql.Driver 16 | username: postgres 17 | password: postgres 18 | hikari.connectionTimeout: 100000 19 | hikari.idleTimeout: 600000 20 | hikari.maxLifetime: 1800000 21 | 22 | liquibase: 23 | enabled: true 24 | change-log: classpath:db/changelog-master.xml 25 | 26 | springdoc: 27 | api-docs: 28 | path: /authentication-docs 29 | swagger-ui: 30 | path: /authentication-docs/swagger-ui-custom.html 31 | 32 | logging.level: 33 | root: INFO 34 | liquibase: INFO -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/service/UserDetailsServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.service; 2 | 3 | import com.mina.authentication.repository.UserRepository; 4 | import com.mina.authentication.domain.User; 5 | import com.mina.authentication.exceptions.NotFoundException; 6 | import org.springframework.security.core.userdetails.UserDetails; 7 | import org.springframework.security.core.userdetails.UserDetailsService; 8 | import org.springframework.stereotype.Service; 9 | 10 | @Service 11 | public class UserDetailsServiceImpl implements UserDetailsService { 12 | 13 | private final UserRepository repository; 14 | 15 | public UserDetailsServiceImpl(UserRepository repository) { 16 | this.repository = repository; 17 | } 18 | 19 | @Override 20 | public UserDetails loadUserByUsername(String email) { 21 | 22 | User user = repository.findByEmail(email).orElseThrow(() -> 23 | new NotFoundException(String.format("User does not exist, email: %s", email))); 24 | 25 | return org.springframework.security.core.userdetails.User.builder() 26 | .username(user.email()) 27 | .password(user.password()) 28 | .build(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.repository; 2 | 3 | import com.mina.authentication.domain.User; 4 | import java.util.Optional; 5 | import org.springframework.jdbc.core.simple.JdbcClient; 6 | import org.springframework.stereotype.Repository; 7 | import org.springframework.util.Assert; 8 | 9 | @Repository 10 | public class UserRepository { 11 | 12 | private static final String INSERT = "INSERT INTO authentication.user (name, email, password) VALUES(:name, :email, :password)"; 13 | private static final String FIND_BY_EMAIL = "SELECT * FROM authentication.user WHERE email = :email"; 14 | 15 | private final JdbcClient jdbcClient; 16 | 17 | public UserRepository(JdbcClient jdbcClient) { 18 | this.jdbcClient = jdbcClient; 19 | } 20 | 21 | public void add(User user) { 22 | long affected = jdbcClient.sql(INSERT) 23 | .param("name", user.name()) 24 | .param("email", user.email()) 25 | .param("password", user.password()) 26 | .update(); 27 | 28 | Assert.isTrue(affected == 1, "Could not add user."); 29 | } 30 | 31 | public Optional findByEmail(String email) { 32 | return jdbcClient.sql(FIND_BY_EMAIL) 33 | .param("email", email) 34 | .query(User.class) 35 | .optional(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/resources/db/changelogs/1_tables.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | CREATE TABLE IF NOT EXISTS authentication.user 9 | ( 10 | id BIGSERIAL NOT NULL PRIMARY KEY, 11 | name VARCHAR(255) NOT NULL, 12 | email VARCHAR(255) NOT NULL, 13 | password VARCHAR(255) NOT NULL, 14 | created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP 15 | ); 16 | 17 | 18 | DROP TABLE authentication.user; 19 | 20 | 21 | 22 | 23 | 24 | CREATE TABLE IF NOT EXISTS authentication.login_attempt 25 | ( 26 | id BIGSERIAL NOT NULL PRIMARY KEY, 27 | email VARCHAR(255) NOT NULL, 28 | success BOOLEAN DEFAULT false, 29 | created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP 30 | ); 31 | 32 | 33 | DROP TABLE authentication.login_attempt; 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/config/SwaggerConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import io.swagger.v3.oas.models.Components; 7 | import io.swagger.v3.oas.models.OpenAPI; 8 | import io.swagger.v3.oas.models.info.Contact; 9 | import io.swagger.v3.oas.models.info.Info; 10 | import io.swagger.v3.oas.models.security.SecurityRequirement; 11 | import io.swagger.v3.oas.models.security.SecurityScheme; 12 | 13 | @Configuration 14 | public class SwaggerConfiguration { 15 | 16 | @Bean 17 | public OpenAPI openAPI() { 18 | return new OpenAPI() 19 | .addSecurityItem(new SecurityRequirement().addList("Bearer Authentication")) 20 | .components(new Components().addSecuritySchemes("Bearer Authentication", createAPIKeyScheme())) 21 | .info(apiInfo()); 22 | } 23 | 24 | private SecurityScheme createAPIKeyScheme() { 25 | return new SecurityScheme().type(SecurityScheme.Type.HTTP) 26 | .bearerFormat("JWT") 27 | .scheme("bearer"); 28 | } 29 | 30 | private Info apiInfo() { 31 | return new Info() 32 | .title("Authentication Service Api Doc") 33 | .version("1.0.0") 34 | .description("HTTP APIs to manage user registration and authentication.") 35 | .contact(new Contact().name("Mina Rashidi")); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/service/UserService.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.service; 2 | 3 | import com.mina.authentication.controller.dto.SignupRequest; 4 | import com.mina.authentication.domain.User; 5 | import com.mina.authentication.exceptions.DuplicateException; 6 | import com.mina.authentication.repository.UserRepository; 7 | import java.util.Optional; 8 | import org.springframework.security.crypto.password.PasswordEncoder; 9 | import org.springframework.stereotype.Service; 10 | import org.springframework.transaction.annotation.Transactional; 11 | 12 | @Service 13 | @Transactional(readOnly = true) 14 | public class UserService { 15 | 16 | private final UserRepository repository; 17 | private final PasswordEncoder passwordEncoder; 18 | 19 | public UserService(UserRepository repository, PasswordEncoder passwordEncoder) { 20 | this.repository = repository; 21 | this.passwordEncoder = passwordEncoder; 22 | } 23 | 24 | @Transactional 25 | public void signup(SignupRequest request) { 26 | String email = request.email(); 27 | Optional existingUser = repository.findByEmail(email); 28 | if (existingUser.isPresent()) { 29 | throw new DuplicateException(String.format("User with the email address '%s' already exists.", email)); 30 | } 31 | 32 | String hashedPassword = passwordEncoder.encode(request.password()); 33 | User user = new User(request.name(), email, hashedPassword); 34 | repository.add(user); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/repository/LoginAttemptRepository.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.repository; 2 | 3 | import com.mina.authentication.domain.LoginAttempt; 4 | import java.util.List; 5 | import org.springframework.jdbc.core.simple.JdbcClient; 6 | import org.springframework.stereotype.Repository; 7 | import org.springframework.util.Assert; 8 | 9 | @Repository 10 | public class LoginAttemptRepository { 11 | 12 | private static final int RECENT_COUNT = 10; // can be in the config 13 | private static final String INSERT = "INSERT INTO authentication.login_attempt (email, success, created_at) VALUES(:email, :success, :createdAt)"; 14 | private static final String FIND_RECENT = "SELECT * FROM authentication.login_attempt WHERE email = :email ORDER BY created_at DESC LIMIT :recentCount"; 15 | 16 | private final JdbcClient jdbcClient; 17 | 18 | public LoginAttemptRepository(JdbcClient jdbcClient) { 19 | this.jdbcClient = jdbcClient; 20 | } 21 | 22 | public void add(LoginAttempt loginAttempt) { 23 | long affected = jdbcClient.sql(INSERT) 24 | .param("email", loginAttempt.email()) 25 | .param("success", loginAttempt.success()) 26 | .param("createdAt", loginAttempt.createdAt()) 27 | .update(); 28 | 29 | Assert.isTrue(affected == 1, "Could not add login attempt."); 30 | } 31 | 32 | public List findRecent(String email) { 33 | return jdbcClient.sql(FIND_RECENT) 34 | .param("email", email) 35 | .param("recentCount", RECENT_COUNT) 36 | .query(LoginAttempt.class) 37 | .list(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/helper/JwtHelper.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.helper; 2 | 3 | import com.mina.authentication.exceptions.AccessDeniedException; 4 | import io.jsonwebtoken.Claims; 5 | import io.jsonwebtoken.ExpiredJwtException; 6 | import io.jsonwebtoken.Jwts; 7 | import io.jsonwebtoken.SignatureAlgorithm; 8 | import io.jsonwebtoken.security.Keys; 9 | import io.jsonwebtoken.security.SignatureException; 10 | import java.security.Key; 11 | import java.time.Instant; 12 | import java.time.temporal.ChronoUnit; 13 | import java.util.Date; 14 | import org.springframework.security.core.userdetails.UserDetails; 15 | 16 | public class JwtHelper { 17 | 18 | private static final Key SECRET_KEY = Keys.secretKeyFor(SignatureAlgorithm.HS256); 19 | private static final int MINUTES = 60; 20 | 21 | public static String generateToken(String email) { 22 | var now = Instant.now(); 23 | return Jwts.builder() 24 | .subject(email) 25 | .issuedAt(Date.from(now)) 26 | .expiration(Date.from(now.plus(MINUTES, ChronoUnit.MINUTES))) 27 | .signWith(SignatureAlgorithm.HS256, SECRET_KEY) 28 | .compact(); 29 | } 30 | 31 | public static String extractUsername(String token) { 32 | return getTokenBody(token).getSubject(); 33 | } 34 | 35 | public static Boolean validateToken(String token, UserDetails userDetails) { 36 | final String username = extractUsername(token); 37 | return username.equals(userDetails.getUsername()) && !isTokenExpired(token); 38 | } 39 | 40 | private static Claims getTokenBody(String token) { 41 | try { 42 | return Jwts 43 | .parser() 44 | .setSigningKey(SECRET_KEY) 45 | .build() 46 | .parseSignedClaims(token) 47 | .getPayload(); 48 | } catch (SignatureException | ExpiredJwtException e) { // Invalid signature or expired token 49 | throw new AccessDeniedException("Access denied: " + e.getMessage()); 50 | } 51 | } 52 | 53 | private static boolean isTokenExpired(String token) { 54 | Claims claims = getTokenBody(token); 55 | return claims.getExpiration().before(new Date()); 56 | } 57 | } -------------------------------------------------------------------------------- /authentication.postman_collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "_postman_id": "61c4c6f2-819a-468d-9b30-3cf1e26b9767", 4 | "name": "authentication", 5 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", 6 | "_exporter_id": "27553088" 7 | }, 8 | "item": [ 9 | { 10 | "name": "signup", 11 | "request": { 12 | "method": "POST", 13 | "header": [], 14 | "body": { 15 | "mode": "raw", 16 | "raw": "{\n \"name\":\"mina\",\n \"email\":\"mina@gmail.com\",\n \"password\":\"123456\"\n}", 17 | "options": { 18 | "raw": { 19 | "language": "json" 20 | } 21 | } 22 | }, 23 | "url": { 24 | "raw": "http://localhost:8080/api/auth/signup", 25 | "protocol": "http", 26 | "host": [ 27 | "localhost" 28 | ], 29 | "port": "8080", 30 | "path": [ 31 | "api", 32 | "auth", 33 | "signup" 34 | ] 35 | } 36 | }, 37 | "response": [] 38 | }, 39 | { 40 | "name": "login", 41 | "protocolProfileBehavior": { 42 | "disabledSystemHeaders": {} 43 | }, 44 | "request": { 45 | "method": "POST", 46 | "header": [ 47 | { 48 | "key": "Content-Type", 49 | "value": "application/json", 50 | "type": "text" 51 | } 52 | ], 53 | "body": { 54 | "mode": "raw", 55 | "raw": "{\n \"email\":\"mina@gmail.com\",\n \"password\":\"123456\"\n}" 56 | }, 57 | "url": { 58 | "raw": "http://localhost:8080/api/auth/login", 59 | "protocol": "http", 60 | "host": [ 61 | "localhost" 62 | ], 63 | "port": "8080", 64 | "path": [ 65 | "api", 66 | "auth", 67 | "login" 68 | ] 69 | } 70 | }, 71 | "response": [] 72 | }, 73 | { 74 | "name": "loginAttempts", 75 | "protocolProfileBehavior": { 76 | "disableBodyPruning": true 77 | }, 78 | "request": { 79 | "method": "GET", 80 | "header": [ 81 | { 82 | "key": "Content-Type", 83 | "value": "application/json", 84 | "type": "text" 85 | }, 86 | { 87 | "key": "Accept", 88 | "value": "application/json", 89 | "type": "text" 90 | }, 91 | { 92 | "key": "Authorization", 93 | "value": "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJtaW5hQGdtYWlsLmNvbSIsImlhdCI6MTcwMjMzMzczMywiZXhwIjoxNzAyMzM3MzMzfQ.0BTByBX6YLu1PWqxbM6oIClAHf-4diNfLqHest_KPYc", 94 | "type": "text" 95 | }, 96 | { 97 | "key": "", 98 | "value": "", 99 | "type": "text", 100 | "disabled": true 101 | } 102 | ], 103 | "body": { 104 | "mode": "raw", 105 | "raw": "{\n \"email\":\"mina@gmail.com\",\n \"password\":\"123456\"\n}", 106 | "options": { 107 | "raw": { 108 | "language": "json" 109 | } 110 | } 111 | }, 112 | "url": { 113 | "raw": "http://localhost:8080/api/auth/loginAttempts", 114 | "protocol": "http", 115 | "host": [ 116 | "localhost" 117 | ], 118 | "port": "8080", 119 | "path": [ 120 | "api", 121 | "auth", 122 | "loginAttempts" 123 | ] 124 | } 125 | }, 126 | "response": [] 127 | } 128 | ] 129 | } -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/controller/RestExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.controller; 2 | 3 | import static org.springframework.http.HttpStatus.BAD_REQUEST; 4 | import static org.springframework.http.HttpStatus.CONFLICT; 5 | import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR; 6 | import static org.springframework.http.HttpStatus.NOT_FOUND; 7 | import static org.springframework.http.HttpStatus.UNAUTHORIZED; 8 | 9 | import com.mina.authentication.controller.dto.ApiErrorResponse; 10 | import com.mina.authentication.exceptions.DuplicateException; 11 | import com.mina.authentication.exceptions.NotFoundException; 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | import org.springframework.http.ResponseEntity; 15 | import org.springframework.security.authentication.BadCredentialsException; 16 | import org.springframework.security.authentication.InternalAuthenticationServiceException; 17 | import org.springframework.web.bind.MethodArgumentNotValidException; 18 | import org.springframework.web.bind.annotation.ControllerAdvice; 19 | import org.springframework.web.bind.annotation.ExceptionHandler; 20 | 21 | @ControllerAdvice 22 | public class RestExceptionHandler { 23 | 24 | @ExceptionHandler(NotFoundException.class) 25 | public ResponseEntity handleNotFoundException(NotFoundException e) { 26 | return ResponseEntity.status(NOT_FOUND).body(new ApiErrorResponse(NOT_FOUND.value(), e.getMessage())); 27 | } 28 | 29 | @ExceptionHandler(MethodArgumentNotValidException.class) 30 | public ResponseEntity handleRequestNotValidException(MethodArgumentNotValidException e) { 31 | 32 | List errors = new ArrayList<>(); 33 | e.getBindingResult() 34 | .getFieldErrors().forEach(error -> errors.add(error.getField() + ": " + error.getDefaultMessage())); 35 | e.getBindingResult() 36 | .getGlobalErrors() //Global errors are not associated with a specific field but are related to the entire object being validated. 37 | .forEach(error -> errors.add(error.getObjectName() + ": " + error.getDefaultMessage())); 38 | 39 | String message = "Validation of request failed: %s".formatted(String.join(", ", errors)); 40 | return ResponseEntity.status(BAD_REQUEST).body(new ApiErrorResponse(BAD_REQUEST.value(), message)); 41 | } 42 | 43 | @ExceptionHandler(BadCredentialsException.class) 44 | public ResponseEntity handleBadCredentialsException() { 45 | return ResponseEntity.status(UNAUTHORIZED) 46 | .body(new ApiErrorResponse(UNAUTHORIZED.value(), "Invalid username or password")); 47 | } 48 | 49 | @ExceptionHandler(DuplicateException.class) 50 | public ResponseEntity handleDuplicateException(DuplicateException e) { 51 | return ResponseEntity.status(CONFLICT).body(new ApiErrorResponse(CONFLICT.value(), e.getMessage())); 52 | } 53 | 54 | @ExceptionHandler(InternalAuthenticationServiceException.class) 55 | public ResponseEntity handleInternalAuthenticationServiceException(InternalAuthenticationServiceException e) { 56 | return ResponseEntity.status(UNAUTHORIZED).body(new ApiErrorResponse(UNAUTHORIZED.value(), e.getMessage())); 57 | } 58 | 59 | @ExceptionHandler(Exception.class) 60 | public ResponseEntity handleUnknownException(Exception e) { 61 | return ResponseEntity.status(INTERNAL_SERVER_ERROR).body(new ApiErrorResponse(INTERNAL_SERVER_ERROR.value(), e.getMessage())); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/config/JwtAuthFilter.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.config; 2 | 3 | import com.fasterxml.jackson.databind.ObjectMapper; 4 | import com.mina.authentication.controller.dto.ApiErrorResponse; 5 | import com.mina.authentication.exceptions.AccessDeniedException; 6 | import com.mina.authentication.helper.JwtHelper; 7 | import com.mina.authentication.service.UserDetailsServiceImpl; 8 | import jakarta.servlet.FilterChain; 9 | import jakarta.servlet.ServletException; 10 | import jakarta.servlet.http.HttpServletRequest; 11 | import jakarta.servlet.http.HttpServletResponse; 12 | import java.io.IOException; 13 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 14 | import org.springframework.security.core.context.SecurityContextHolder; 15 | import org.springframework.security.core.userdetails.UserDetails; 16 | import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; 17 | import org.springframework.stereotype.Component; 18 | import org.springframework.web.filter.OncePerRequestFilter; 19 | 20 | @Component 21 | public class JwtAuthFilter extends OncePerRequestFilter { 22 | 23 | private final UserDetailsServiceImpl userDetailsService; 24 | private final ObjectMapper objectMapper; 25 | 26 | public JwtAuthFilter(UserDetailsServiceImpl userDetailsService, ObjectMapper objectMapper) { 27 | this.userDetailsService = userDetailsService; 28 | this.objectMapper = objectMapper; 29 | } 30 | 31 | @Override 32 | protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 33 | throws ServletException, IOException { 34 | try { 35 | String authHeader = request.getHeader("Authorization"); 36 | 37 | String token = null; 38 | String username = null; 39 | if (authHeader != null && authHeader.startsWith("Bearer ")) { 40 | token = authHeader.substring(7); 41 | username = JwtHelper.extractUsername(token); 42 | } 43 | 44 | // If the accessToken is null. It will pass the request to next filter in the chain. 45 | // Any login and signup requests will not have jwt token in their header, therefore they will be passed to next filter chain. 46 | if (token == null) { 47 | filterChain.doFilter(request, response); 48 | return; 49 | } 50 | 51 | // If any accessToken is present, then it will validate the token and then authenticate the request in security context 52 | if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { 53 | UserDetails userDetails = userDetailsService.loadUserByUsername(username); 54 | if (JwtHelper.validateToken(token, userDetails)) { 55 | UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, null); 56 | authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); 57 | SecurityContextHolder.getContext().setAuthentication(authenticationToken); 58 | } 59 | } 60 | 61 | filterChain.doFilter(request, response); 62 | } catch (AccessDeniedException e) { 63 | ApiErrorResponse errorResponse = new ApiErrorResponse(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); 64 | response.setStatus(HttpServletResponse.SC_FORBIDDEN); 65 | response.getWriter().write(toJson(errorResponse)); 66 | } 67 | } 68 | 69 | private String toJson(ApiErrorResponse response) { 70 | try { 71 | return objectMapper.writeValueAsString(response); 72 | } catch (Exception e) { 73 | return ""; // Return an empty string if serialization fails 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/config/SecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.config; 2 | 3 | import com.mina.authentication.service.UserDetailsServiceImpl; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.http.HttpMethod; 7 | import org.springframework.security.authentication.AuthenticationManager; 8 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 9 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 10 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 11 | import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; 12 | import org.springframework.security.config.http.SessionCreationPolicy; 13 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 14 | import org.springframework.security.crypto.password.PasswordEncoder; 15 | import org.springframework.security.web.SecurityFilterChain; 16 | import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; 17 | 18 | @Configuration 19 | @EnableWebSecurity 20 | public class SecurityConfig { 21 | 22 | private final UserDetailsServiceImpl userDetailsService; 23 | private final JwtAuthFilter jwtAuthFilter; 24 | 25 | public SecurityConfig(UserDetailsServiceImpl userDetailsService, JwtAuthFilter jwtAuthFilter) { 26 | this.userDetailsService = userDetailsService; 27 | this.jwtAuthFilter = jwtAuthFilter; 28 | } 29 | 30 | @Bean 31 | public PasswordEncoder passwordEncoder() { 32 | return new BCryptPasswordEncoder(); 33 | } 34 | 35 | @Bean 36 | public SecurityFilterChain filterChain(HttpSecurity http, AuthenticationManager authenticationManager) throws Exception { 37 | return http 38 | .cors(AbstractHttpConfigurer::disable) 39 | .csrf(AbstractHttpConfigurer::disable) 40 | .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) 41 | // Set permissions on endpoints 42 | .authorizeHttpRequests(auth -> auth 43 | // our public endpoints 44 | .requestMatchers(HttpMethod.POST, "/api/auth/signup/**").permitAll() 45 | .requestMatchers(HttpMethod.POST, "/api/auth/login/**").permitAll() 46 | .requestMatchers(HttpMethod.GET, "/authentication-docs/**").permitAll() 47 | // our private endpoints 48 | .anyRequest().authenticated()) 49 | .authenticationManager(authenticationManager) 50 | 51 | // We need jwt filter before the UsernamePasswordAuthenticationFilter. 52 | // Since we need every request to be authenticated before going through spring security filter. 53 | // (UsernamePasswordAuthenticationFilter creates a UsernamePasswordAuthenticationToken from a username and password that are submitted in the HttpServletRequest.) 54 | .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class) 55 | .build(); 56 | } 57 | 58 | @Bean 59 | public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception { 60 | AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class); 61 | authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); 62 | return authenticationManagerBuilder.build(); 63 | } 64 | } 65 | 66 | // CORS(Cross-origin resource sharing) is just to avoid if you run javascript across different domains like if you execute JS on http://testpage.com and access http://anotherpage.com 67 | // CSRF(Cross-Site Request Forgery) -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 3.2.0 9 | 10 | 11 | com.mina 12 | authentication 13 | 0.0.1-SNAPSHOT 14 | authentication 15 | authentication 16 | 17 | 18 | 21 19 | 2.2.0 20 | 0.12.3 21 | 22 | 23 | 24 | 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-web 29 | 30 | 31 | 32 | org.springframework.boot 33 | spring-boot-starter-security 34 | 35 | 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-jdbc 40 | 41 | 42 | 43 | org.postgresql 44 | postgresql 45 | 46 | 47 | 48 | org.liquibase 49 | liquibase-core 50 | 51 | 52 | 53 | 54 | io.jsonwebtoken 55 | jjwt-api 56 | ${jwt.version} 57 | 58 | 59 | io.jsonwebtoken 60 | jjwt-impl 61 | ${jwt.version} 62 | runtime 63 | 64 | 65 | io.jsonwebtoken 66 | jjwt-jackson 67 | ${jwt.version} 68 | runtime 69 | 70 | 71 | 72 | 73 | org.springframework.boot 74 | spring-boot-starter-validation 75 | 76 | 77 | 78 | 79 | org.springdoc 80 | springdoc-openapi-starter-webmvc-ui 81 | ${spring-doc.version} 82 | 83 | 84 | 85 | 86 | org.springframework.boot 87 | spring-boot-starter-test 88 | test 89 | 90 | 91 | org.springframework 92 | spring-webflux 93 | test 94 | 95 | 96 | org.springframework.boot 97 | spring-boot-testcontainers 98 | test 99 | 100 | 101 | org.testcontainers 102 | junit-jupiter 103 | test 104 | 105 | 106 | org.testcontainers 107 | postgresql 108 | test 109 | 110 | 111 | 112 | 113 | 114 | 115 | org.springframework.boot 116 | spring-boot-maven-plugin 117 | 118 | 119 | 120 | 121 | 122 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Authentication Service 2 | 3 | Authentication service is a Spring Boot application to manage user registration and authentication. 4 | Expose APIs for user registration , authenticating registered users and to retrieve the 10 most recent login attempts for a user. 5 | 6 | --- 7 | 8 | ### Technologies / Changes 9 | 10 | * Java 21 11 | * Spring Boot 3.2(with virtual threads) 12 | * Maven 13 | * Use docker-compose 14 | * TestContainers for Integration Tests 15 | * JDBC Client 16 | * Swagger API documentation 17 | * TODO: Monitoring and Observability using Spring Boot Actuator and Micrometer 18 | 19 | --- 20 | 21 | ### How to Build 22 | 23 | - Navigate to the root directory and run: `./mvn clean install` 24 | 25 | ### How to Run 26 | 27 | 1. Change to `/scripts` 28 | 2. run `./start-services.sh` 29 | 3. Run `./create-database.sh` 30 | 4. Launch the application using: `mvn spring-boot:run` 31 | 5. To interact with the database, you can run: 32 | - `docker ps` to obtain the Container ID for the postgres image, then execute: 33 | - `docker exec -it ${containerId} psql authentication -U postgres` 34 | - While in the container, run `\dt authentication.` to view the list of created tables. 35 | ```sql 36 | select * from authentication.user; 37 | select * from authentication.login_attempt; 38 | ``` 39 | 40 | ### API Documentation 41 | 42 | Swagger: Access the Swagger API documentation 43 | at: [http://localhost:8080/authentication-docs/swagger-ui/index.html](http://localhost:8080/authentication-docs/swagger-ui/index.html) when 44 | the application is running. 45 | 46 | (Note: to test `loginAttempts` endpoint, grab the returned JWT token from the `login` endpoint, then just click on the `Authorize` button and paste the token) 47 | 48 | [Postman Collection](authentication.postman_collection.json) 49 | 50 | [Sequence diagram](authentication-sequence-diagram.png) 51 | 52 | --- 53 | 54 | ### Design Decisions 55 | 56 | **Backend Service** 57 | I have used Spring Boot 3.2(Spring MVC), which was released recently and added support for Virtual Threads on JDK 21. 58 | (To use Virtual Threads, I just set the property `spring.threads.virtual.enabled` to `true`.) 59 | 60 | Our Tomcat will use virtual threads for HTTP requests, means our application runs on virtual threads to achieve high throughput. 61 | 62 | **JDBC Client** is used, since Spring Framework 6.1 introduced JDBC Client that gives us a fluent API for talking to a database. 63 | 64 | **API Clients** 65 | * Integration tests to call the authentication APIs. 66 | * Swagger is used to call the endpoints. 67 | * Postman collection are also included. 68 | 69 | **Service(Client) to service(backend) communication** 70 | There are two ways to call backend APIs: 71 | 72 | * Spring MVC app(Servlet stack) 73 | * old way: Rest template(feature complete; a lot of overloaded methods(confusing) for making service call) 74 | * new way: Rest Client(Fluent API) 75 | 76 | * Spring Webflux(Reactive stack) 77 | Web Client(Fluent API) 78 | 79 | In a real-world application, we might need to have a separate (frontend) application to interact with backend service. 80 | 81 | --- 82 | 83 | ### The Need for Monitoring and Observability 84 | 85 | We need to establish robust monitoring and observability solutions. 86 | By implementing these, we can gain insights into the performance and behavior of our application. 87 | 88 | #### Metrics 89 | 90 | I recommend to set up Prometheus as the monitoring backend and Grafana for creating informative dashboards to visualize and analyze data. 91 | Metrics should be exposed through HTTP, and Prometheus can be configured to scrape data at regular intervals from the /prometheus endpoint. 92 | 93 | We can take advantage of Spring Boot production-ready features that are packed in a module 94 | called actuator https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html. 95 | 96 | #### Tracing 97 | 98 | We can use micrometer-tracing, which provides a simple facade for the most popular tracer libraries, and letting us instrument our 99 | application code without vendor lock-in. 100 | https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html#actuator.micrometer-tracing 101 | -------------------------------------------------------------------------------- /src/main/java/com/mina/authentication/controller/AuthController.java: -------------------------------------------------------------------------------- 1 | 2 | package com.mina.authentication.controller; 3 | 4 | import com.mina.authentication.controller.dto.SignupRequest; 5 | import com.mina.authentication.helper.JwtHelper; 6 | import com.mina.authentication.service.UserService; 7 | import com.mina.authentication.controller.dto.ApiErrorResponse; 8 | import com.mina.authentication.controller.dto.LoginAttemptResponse; 9 | import com.mina.authentication.controller.dto.LoginRequest; 10 | import com.mina.authentication.controller.dto.LoginResponse; 11 | import com.mina.authentication.domain.LoginAttempt; 12 | import com.mina.authentication.service.LoginService; 13 | import io.swagger.v3.oas.annotations.Operation; 14 | import io.swagger.v3.oas.annotations.media.Content; 15 | import io.swagger.v3.oas.annotations.media.Schema; 16 | import io.swagger.v3.oas.annotations.responses.ApiResponse; 17 | import jakarta.validation.Valid; 18 | import java.util.List; 19 | import java.util.stream.Collectors; 20 | import org.springframework.http.HttpStatus; 21 | import org.springframework.http.MediaType; 22 | import org.springframework.http.ResponseEntity; 23 | import org.springframework.security.authentication.AuthenticationManager; 24 | import org.springframework.security.authentication.BadCredentialsException; 25 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; 26 | import org.springframework.web.bind.annotation.GetMapping; 27 | import org.springframework.web.bind.annotation.PostMapping; 28 | import org.springframework.web.bind.annotation.RequestBody; 29 | import org.springframework.web.bind.annotation.RequestHeader; 30 | import org.springframework.web.bind.annotation.RequestMapping; 31 | import org.springframework.web.bind.annotation.RestController; 32 | 33 | @RestController 34 | @RequestMapping(path = "/api/auth", produces = MediaType.APPLICATION_JSON_VALUE) 35 | public class AuthController { 36 | 37 | private final AuthenticationManager authenticationManager; 38 | private final UserService userService; 39 | private final LoginService loginService; 40 | 41 | public AuthController(AuthenticationManager authenticationManager, UserService userService, LoginService loginService) { 42 | this.authenticationManager = authenticationManager; 43 | this.userService = userService; 44 | this.loginService = loginService; 45 | } 46 | 47 | @Operation(summary = "Signup user") 48 | @ApiResponse(responseCode = "201") 49 | @ApiResponse(responseCode = "404", content = @Content(schema = @Schema(implementation = ApiErrorResponse.class))) 50 | @ApiResponse(responseCode = "409", content = @Content(schema = @Schema(implementation = ApiErrorResponse.class))) 51 | @ApiResponse(responseCode = "500", content = @Content(schema = @Schema(implementation = ApiErrorResponse.class))) 52 | @PostMapping("/signup") 53 | public ResponseEntity signup(@Valid @RequestBody SignupRequest requestDto) { 54 | userService.signup(requestDto); 55 | return ResponseEntity.status(HttpStatus.CREATED).build(); 56 | } 57 | 58 | @Operation(summary = "Authenticate user and return token") 59 | @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = LoginResponse.class))) 60 | @ApiResponse(responseCode = "401", content = @Content(schema = @Schema(implementation = ApiErrorResponse.class))) 61 | @ApiResponse(responseCode = "404", content = @Content(schema = @Schema(implementation = ApiErrorResponse.class))) 62 | @ApiResponse(responseCode = "500", content = @Content(schema = @Schema(implementation = ApiErrorResponse.class))) 63 | @PostMapping(value = "/login") 64 | public ResponseEntity login(@Valid @RequestBody LoginRequest request) { 65 | try { 66 | authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.email(), request.password())); 67 | } catch (BadCredentialsException e) { 68 | loginService.addLoginAttempt(request.email(), false); 69 | throw e; 70 | } 71 | 72 | String token = JwtHelper.generateToken(request.email()); 73 | loginService.addLoginAttempt(request.email(), true); 74 | return ResponseEntity.ok(new LoginResponse(request.email(), token)); 75 | } 76 | 77 | @Operation(summary = "Get recent login attempts") 78 | @ApiResponse(responseCode = "200", content = @Content(schema = @Schema(implementation = LoginResponse.class))) 79 | @ApiResponse(responseCode = "403", content = @Content(schema = @Schema(implementation = ApiErrorResponse.class)))//forbidden 80 | @ApiResponse(responseCode = "500", content = @Content(schema = @Schema(implementation = ApiErrorResponse.class))) 81 | @GetMapping(value = "/loginAttempts") 82 | public ResponseEntity> loginAttempts(@RequestHeader("Authorization") String token) { 83 | String email = JwtHelper.extractUsername(token.replace("Bearer ", "")); 84 | List loginAttempts = loginService.findRecentLoginAttempts(email); 85 | return ResponseEntity.ok(convertToDTOs(loginAttempts)); 86 | } 87 | 88 | private List convertToDTOs(List loginAttempts) { 89 | return loginAttempts.stream() 90 | .map(LoginAttemptResponse::convertToDTO) 91 | .collect(Collectors.toList()); 92 | } 93 | } -------------------------------------------------------------------------------- /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 Apache Maven Wrapper startup batch script, version 3.2.0 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 MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 28 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 29 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 30 | @REM e.g. to debug Maven itself, use 31 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 32 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 33 | @REM ---------------------------------------------------------------------------- 34 | 35 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 36 | @echo off 37 | @REM set title of command window 38 | title %0 39 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 40 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 41 | 42 | @REM set %HOME% to equivalent of $HOME 43 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 44 | 45 | @REM Execute a user defined script before this one 46 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 47 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 48 | if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* 49 | if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* 50 | :skipRcPre 51 | 52 | @setlocal 53 | 54 | set ERROR_CODE=0 55 | 56 | @REM To isolate internal variables from possible post scripts, we use another setlocal 57 | @setlocal 58 | 59 | @REM ==== START VALIDATION ==== 60 | if not "%JAVA_HOME%" == "" goto OkJHome 61 | 62 | echo. 63 | echo Error: JAVA_HOME not found in your environment. >&2 64 | echo Please set the JAVA_HOME variable in your environment to match the >&2 65 | echo location of your Java installation. >&2 66 | echo. 67 | goto error 68 | 69 | :OkJHome 70 | if exist "%JAVA_HOME%\bin\java.exe" goto init 71 | 72 | echo. 73 | echo Error: JAVA_HOME is set to an invalid directory. >&2 74 | echo JAVA_HOME = "%JAVA_HOME%" >&2 75 | echo Please set the JAVA_HOME variable in your environment to match the >&2 76 | echo location of your Java installation. >&2 77 | echo. 78 | goto error 79 | 80 | @REM ==== END VALIDATION ==== 81 | 82 | :init 83 | 84 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 85 | @REM Fallback to current working directory if not found. 86 | 87 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 88 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 89 | 90 | set EXEC_DIR=%CD% 91 | set WDIR=%EXEC_DIR% 92 | :findBaseDir 93 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 94 | cd .. 95 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 96 | set WDIR=%CD% 97 | goto findBaseDir 98 | 99 | :baseDirFound 100 | set MAVEN_PROJECTBASEDIR=%WDIR% 101 | cd "%EXEC_DIR%" 102 | goto endDetectBaseDir 103 | 104 | :baseDirNotFound 105 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 106 | cd "%EXEC_DIR%" 107 | 108 | :endDetectBaseDir 109 | 110 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 111 | 112 | @setlocal EnableExtensions EnableDelayedExpansion 113 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 114 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 115 | 116 | :endReadAdditionalConfig 117 | 118 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" 123 | 124 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 125 | IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B 126 | ) 127 | 128 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 129 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 130 | if exist %WRAPPER_JAR% ( 131 | if "%MVNW_VERBOSE%" == "true" ( 132 | echo Found %WRAPPER_JAR% 133 | ) 134 | ) else ( 135 | if not "%MVNW_REPOURL%" == "" ( 136 | SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" 137 | ) 138 | if "%MVNW_VERBOSE%" == "true" ( 139 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 140 | echo Downloading from: %WRAPPER_URL% 141 | ) 142 | 143 | powershell -Command "&{"^ 144 | "$webclient = new-object System.Net.WebClient;"^ 145 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 146 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 147 | "}"^ 148 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ 149 | "}" 150 | if "%MVNW_VERBOSE%" == "true" ( 151 | echo Finished downloading %WRAPPER_JAR% 152 | ) 153 | ) 154 | @REM End of extension 155 | 156 | @REM If specified, validate the SHA-256 sum of the Maven wrapper jar file 157 | SET WRAPPER_SHA_256_SUM="" 158 | FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 159 | IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B 160 | ) 161 | IF NOT %WRAPPER_SHA_256_SUM%=="" ( 162 | powershell -Command "&{"^ 163 | "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ 164 | "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ 165 | " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ 166 | " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ 167 | " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ 168 | " exit 1;"^ 169 | "}"^ 170 | "}" 171 | if ERRORLEVEL 1 goto error 172 | ) 173 | 174 | @REM Provide a "standardized" way to retrieve the CLI args that will 175 | @REM work with both Windows and non-Windows executions. 176 | set MAVEN_CMD_LINE_ARGS=%* 177 | 178 | %MAVEN_JAVA_EXE% ^ 179 | %JVM_CONFIG_MAVEN_PROPS% ^ 180 | %MAVEN_OPTS% ^ 181 | %MAVEN_DEBUG_OPTS% ^ 182 | -classpath %WRAPPER_JAR% ^ 183 | "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ 184 | %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 185 | if ERRORLEVEL 1 goto error 186 | goto end 187 | 188 | :error 189 | set ERROR_CODE=1 190 | 191 | :end 192 | @endlocal & set ERROR_CODE=%ERROR_CODE% 193 | 194 | if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost 195 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 196 | if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" 197 | if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" 198 | :skipRcPost 199 | 200 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 201 | if "%MAVEN_BATCH_PAUSE%"=="on" pause 202 | 203 | if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% 204 | 205 | cmd /C exit /B %ERROR_CODE% 206 | -------------------------------------------------------------------------------- /src/test/java/com/mina/authentication/controller/AuthControllerIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package com.mina.authentication.controller; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import com.mina.authentication.controller.dto.ApiErrorResponse; 6 | import com.mina.authentication.controller.dto.LoginResponse; 7 | import com.mina.authentication.controller.dto.LoginAttemptResponse; 8 | import java.util.List; 9 | import org.junit.jupiter.api.BeforeEach; 10 | import org.junit.jupiter.api.Test; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient; 13 | import org.springframework.boot.test.context.SpringBootTest; 14 | import org.springframework.boot.testcontainers.service.connection.ServiceConnection; 15 | import org.springframework.http.MediaType; 16 | import org.springframework.test.context.ActiveProfiles; 17 | import org.springframework.test.web.reactive.server.WebTestClient; 18 | import org.testcontainers.containers.PostgreSQLContainer; 19 | import org.testcontainers.junit.jupiter.Container; 20 | import org.testcontainers.junit.jupiter.Testcontainers; 21 | 22 | @Testcontainers 23 | @ActiveProfiles("test") 24 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 25 | @AutoConfigureWebTestClient 26 | public class AuthControllerIntegrationTest { 27 | 28 | static final String SIGNUP_URL = "/api/auth/signup"; 29 | static final String LOGIN_URL = "/api/auth/login"; 30 | static final String LOGIN_ATTEMPTS_URL = "/api/auth/loginAttempts"; 31 | private static final int VALIDATION_ERROR_CODE = 400; 32 | 33 | @Autowired 34 | private WebTestClient webTestClient; 35 | 36 | @Container 37 | @ServiceConnection 38 | private static PostgreSQLContainer postgres = new PostgreSQLContainer<>("postgres:13"); 39 | 40 | @BeforeEach 41 | private void cleanup(){ 42 | // logic 43 | } 44 | // Test signup endpoint 45 | @Test 46 | public void shouldSignupUser() { 47 | String request = """ 48 | { 49 | "name": "mina", 50 | "email": "mina@gmail.com", 51 | "password": "123456" 52 | } 53 | """; 54 | webTestClient 55 | .post().uri(SIGNUP_URL) 56 | .contentType(MediaType.APPLICATION_JSON) 57 | .bodyValue(request) 58 | .exchange() 59 | .expectStatus() 60 | .isCreated(); 61 | } 62 | 63 | @Test 64 | public void shouldReturnDuplicate_onExistingEmail() { 65 | // signup user 66 | String request = """ 67 | { 68 | "name": "sandra", 69 | "email": "sandra@gmail.com", 70 | "password": "123456" 71 | } 72 | """; 73 | webTestClient 74 | .post().uri(SIGNUP_URL) 75 | .contentType(MediaType.APPLICATION_JSON) 76 | .bodyValue(request) 77 | .exchange() 78 | .expectStatus() 79 | .isCreated(); 80 | 81 | // signup another user with duplicate email 82 | String requestWithSameEmail = """ 83 | { 84 | "name": "Anna", 85 | "email": "sandra@gmail.com", 86 | "password": "654321" 87 | } 88 | """; 89 | ApiErrorResponse errorResponse = webTestClient 90 | .post().uri(SIGNUP_URL) 91 | .contentType(MediaType.APPLICATION_JSON) 92 | .bodyValue(requestWithSameEmail) 93 | .exchange() 94 | .expectStatus() 95 | .is4xxClientError() 96 | .expectBody(ApiErrorResponse.class) 97 | .returnResult() 98 | .getResponseBody(); 99 | 100 | assertThat(errorResponse).isNotNull(); 101 | assertThat(errorResponse.errorCode()).isEqualTo(409); 102 | assertThat(errorResponse.description()).isEqualTo("User with the email address 'sandra@gmail.com' already exists."); 103 | } 104 | 105 | @Test 106 | public void shouldReturnBadRequest_WhenSignupRequestIsNotValid() { 107 | String request = """ 108 | { 109 | "name": " ", 110 | "email": "mina@", 111 | "password": "456" 112 | } 113 | """; 114 | ApiErrorResponse errorResponse = webTestClient 115 | .post().uri(SIGNUP_URL) 116 | .contentType(MediaType.APPLICATION_JSON) 117 | .bodyValue(request) 118 | .exchange() 119 | .expectStatus() 120 | .is4xxClientError() 121 | .expectBody(ApiErrorResponse.class) 122 | .returnResult() 123 | .getResponseBody(); 124 | 125 | assertThat(errorResponse).isNotNull(); 126 | assertThat(errorResponse.errorCode()).isEqualTo(VALIDATION_ERROR_CODE); 127 | assertThat(errorResponse.description()).contains( 128 | "password: Password must be between 6 and 20 characters", 129 | "email: Invalid email format", 130 | "name: Name cannot be blank"); 131 | } 132 | 133 | // Test login endpoint 134 | @Test 135 | public void shouldReturnJWTToken_WhenUserIsRegistered() { 136 | String signupRequest = """ 137 | { 138 | "name": "nick", 139 | "email": "nick@gmail.com", 140 | "password": "123456" 141 | } 142 | """; 143 | webTestClient 144 | .post().uri(SIGNUP_URL) 145 | .contentType(MediaType.APPLICATION_JSON) 146 | .bodyValue(signupRequest) 147 | .exchange() 148 | .expectStatus() 149 | .isCreated(); 150 | 151 | String loginRequest = """ 152 | { 153 | "email": "nick@gmail.com", 154 | "password": "123456" 155 | } 156 | """; 157 | LoginResponse loginResponse = webTestClient 158 | .post().uri(LOGIN_URL) 159 | .contentType(MediaType.APPLICATION_JSON) 160 | .bodyValue(loginRequest) 161 | .exchange() 162 | .expectStatus() 163 | .isOk() 164 | .expectBody(LoginResponse.class) 165 | .returnResult() 166 | .getResponseBody(); 167 | 168 | assertThat(loginResponse).isNotNull(); 169 | assertThat(loginResponse.token()).isNotBlank(); 170 | } 171 | 172 | @Test 173 | public void shouldReturnBadCredential() { 174 | String signupRequest = """ 175 | { 176 | "name": "john", 177 | "email": "john@gmail.com", 178 | "password": "123456" 179 | } 180 | """; 181 | webTestClient 182 | .post().uri(SIGNUP_URL) 183 | .contentType(MediaType.APPLICATION_JSON) 184 | .bodyValue(signupRequest) 185 | .exchange() 186 | .expectStatus() 187 | .isCreated(); 188 | 189 | String loginRequestWithWrongPassword = """ 190 | { 191 | "email": "john@gmail.com", 192 | "password": "12345678910" 193 | } 194 | """; 195 | ApiErrorResponse errorResponse = webTestClient 196 | .post().uri(LOGIN_URL) 197 | .contentType(MediaType.APPLICATION_JSON) 198 | .bodyValue(loginRequestWithWrongPassword) 199 | .exchange() 200 | .expectStatus() 201 | .isUnauthorized() 202 | .expectBody(ApiErrorResponse.class) 203 | .returnResult() 204 | .getResponseBody(); 205 | 206 | assertThat(errorResponse).isNotNull(); 207 | assertThat(errorResponse.errorCode()).isEqualTo(401); 208 | assertThat(errorResponse.description()).isEqualTo("Invalid username or password"); 209 | } 210 | 211 | @Test 212 | public void shouldReturnUnauthorized_WhenUserNotRegistered() { 213 | String request = """ 214 | { 215 | "email": "sara@gmail.com", 216 | "password": "123456" 217 | } 218 | """; 219 | ApiErrorResponse errorResponse = webTestClient 220 | .post().uri(LOGIN_URL) 221 | .contentType(MediaType.APPLICATION_JSON) 222 | .bodyValue(request) 223 | .exchange() 224 | .expectStatus() 225 | .isUnauthorized() 226 | .expectBody(ApiErrorResponse.class) 227 | .returnResult() 228 | .getResponseBody(); 229 | 230 | assertThat(errorResponse).isNotNull(); 231 | assertThat(errorResponse.errorCode()).isEqualTo(401); 232 | assertThat(errorResponse.description()).isEqualTo("User does not exist, email: sara@gmail.com"); 233 | } 234 | 235 | // Test loginAttempts endpoint 236 | @Test 237 | public void shouldReturnLoginAttempts_WhenUserIsRegistered() { 238 | String signupRequest = """ 239 | { 240 | "name": "william", 241 | "email": "william@gmail.com", 242 | "password": "123456" 243 | } 244 | """; 245 | webTestClient 246 | .post().uri(SIGNUP_URL) 247 | .contentType(MediaType.APPLICATION_JSON) 248 | .bodyValue(signupRequest) 249 | .exchange() 250 | .expectStatus() 251 | .isCreated(); 252 | 253 | String loginRequest = """ 254 | { 255 | "email": "william@gmail.com", 256 | "password": "123456" 257 | } 258 | """; 259 | LoginResponse loginResponse = webTestClient 260 | .post().uri(LOGIN_URL) 261 | .contentType(MediaType.APPLICATION_JSON) 262 | .bodyValue(loginRequest) 263 | .exchange() 264 | .expectStatus() 265 | .isOk() 266 | .expectBody(LoginResponse.class) 267 | .returnResult() 268 | .getResponseBody(); 269 | assertThat(loginResponse).isNotNull(); 270 | assertThat(loginResponse.token()).isNotBlank(); 271 | 272 | List loginAttemptsResponse = webTestClient 273 | .get().uri(LOGIN_ATTEMPTS_URL) 274 | .header("Authorization", "Bearer " + loginResponse.token()) 275 | .exchange() 276 | .expectStatus() 277 | .isOk() 278 | .expectBodyList(LoginAttemptResponse.class) 279 | .returnResult() 280 | .getResponseBody(); 281 | 282 | assertThat(loginAttemptsResponse).isNotNull(); 283 | assertThat(loginAttemptsResponse).isNotEmpty(); 284 | 285 | LoginAttemptResponse firstLoginAttempt = loginAttemptsResponse.get(0); 286 | assertThat(firstLoginAttempt).isNotNull(); 287 | assertThat(firstLoginAttempt.createdAt()).isNotNull(); 288 | assertThat(firstLoginAttempt.success()).isTrue(); 289 | } 290 | 291 | @Test 292 | public void shouldReturnUnauthorized_withNoAuthorizationHeader() { 293 | webTestClient 294 | .get().uri(LOGIN_ATTEMPTS_URL) 295 | // .header("Authorization", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJtaW5hQGdtYWlsLmNvbSIsImlhdCI6MTcwMjMwMjE0MCwiZXhwIjoxNzAyMzA1NzQwfQ.P0dlSC385lgtyRAr9Ako_hocxa2CvBV_hPAj-RjNtTw") 296 | .exchange() 297 | .expectStatus() 298 | .isForbidden(); 299 | 300 | // String errorResponse = webTestClient 301 | // .get().uri(LOGIN_ATTEMPTS_URL) 302 | //// .header("Authorization", "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJtaW5hQGdtYWlsLmNvbSIsImlhdCI6MTcwMjMwMjE0MCwiZXhwIjoxNzAyMzA1NzQwfQ.P0dlSC385lgtyRAr9Ako_hocxa2CvBV_hPAj-RjNtTw") 303 | // .exchange() 304 | // .expectStatus() 305 | // .isForbidden() 306 | // .expectBody(String.class) 307 | // .returnResult() 308 | // .getResponseBody(); 309 | // 310 | // assertThat(errorResponse).isNotNull(); 311 | // assertThat(errorResponse).isEqualTo("{\"errorCode\":401,\"description\":\"Access denied: Authorization header is required.\"}"); 312 | } 313 | 314 | @Test 315 | public void shouldReturnUnauthorized_withEmptyAuthorizationHeader() { 316 | webTestClient 317 | .get().uri(LOGIN_ATTEMPTS_URL) 318 | .header("Authorization", " ") 319 | .exchange() 320 | .expectStatus() 321 | .isForbidden(); 322 | 323 | // String errorResponse = webTestClient 324 | // .get().uri(LOGIN_ATTEMPTS_URL) 325 | // .header("Authorization", " ") 326 | // .exchange() 327 | // .expectStatus() 328 | // .isUnauthorized() 329 | // .expectBody(String.class) 330 | // .returnResult() 331 | // .getResponseBody(); 332 | // 333 | // assertThat(errorResponse).isNotNull(); 334 | // assertThat(errorResponse).isEqualTo("{\"errorCode\":401,\"description\":\"Access denied: Authorization header is required.\"}"); 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /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 | # Apache Maven Wrapper startup batch script, version 3.2.0 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | # e.g. to debug Maven itself, use 32 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | # ---------------------------------------------------------------------------- 35 | 36 | if [ -z "$MAVEN_SKIP_RC" ] ; then 37 | 38 | if [ -f /usr/local/etc/mavenrc ] ; then 39 | . /usr/local/etc/mavenrc 40 | fi 41 | 42 | if [ -f /etc/mavenrc ] ; then 43 | . /etc/mavenrc 44 | fi 45 | 46 | if [ -f "$HOME/.mavenrc" ] ; then 47 | . "$HOME/.mavenrc" 48 | fi 49 | 50 | fi 51 | 52 | # OS specific support. $var _must_ be set to either true or false. 53 | cygwin=false; 54 | darwin=false; 55 | mingw=false 56 | case "$(uname)" in 57 | CYGWIN*) cygwin=true ;; 58 | MINGW*) mingw=true;; 59 | Darwin*) darwin=true 60 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 61 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 62 | if [ -z "$JAVA_HOME" ]; then 63 | if [ -x "/usr/libexec/java_home" ]; then 64 | JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME 65 | else 66 | JAVA_HOME="/Library/Java/Home"; export JAVA_HOME 67 | fi 68 | fi 69 | ;; 70 | esac 71 | 72 | if [ -z "$JAVA_HOME" ] ; then 73 | if [ -r /etc/gentoo-release ] ; then 74 | JAVA_HOME=$(java-config --jre-home) 75 | fi 76 | fi 77 | 78 | # For Cygwin, ensure paths are in UNIX format before anything is touched 79 | if $cygwin ; then 80 | [ -n "$JAVA_HOME" ] && 81 | JAVA_HOME=$(cygpath --unix "$JAVA_HOME") 82 | [ -n "$CLASSPATH" ] && 83 | CLASSPATH=$(cygpath --path --unix "$CLASSPATH") 84 | fi 85 | 86 | # For Mingw, ensure paths are in UNIX format before anything is touched 87 | if $mingw ; then 88 | [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] && 89 | JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)" 90 | fi 91 | 92 | if [ -z "$JAVA_HOME" ]; then 93 | javaExecutable="$(which javac)" 94 | if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then 95 | # readlink(1) is not available as standard on Solaris 10. 96 | readLink=$(which readlink) 97 | if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then 98 | if $darwin ; then 99 | javaHome="$(dirname "\"$javaExecutable\"")" 100 | javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac" 101 | else 102 | javaExecutable="$(readlink -f "\"$javaExecutable\"")" 103 | fi 104 | javaHome="$(dirname "\"$javaExecutable\"")" 105 | javaHome=$(expr "$javaHome" : '\(.*\)/bin') 106 | JAVA_HOME="$javaHome" 107 | export JAVA_HOME 108 | fi 109 | fi 110 | fi 111 | 112 | if [ -z "$JAVACMD" ] ; then 113 | if [ -n "$JAVA_HOME" ] ; then 114 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 115 | # IBM's JDK on AIX uses strange locations for the executables 116 | JAVACMD="$JAVA_HOME/jre/sh/java" 117 | else 118 | JAVACMD="$JAVA_HOME/bin/java" 119 | fi 120 | else 121 | JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)" 122 | fi 123 | fi 124 | 125 | if [ ! -x "$JAVACMD" ] ; then 126 | echo "Error: JAVA_HOME is not defined correctly." >&2 127 | echo " We cannot execute $JAVACMD" >&2 128 | exit 1 129 | fi 130 | 131 | if [ -z "$JAVA_HOME" ] ; then 132 | echo "Warning: JAVA_HOME environment variable is not set." 133 | fi 134 | 135 | # traverses directory structure from process work directory to filesystem root 136 | # first directory with .mvn subdirectory is considered project base directory 137 | find_maven_basedir() { 138 | if [ -z "$1" ] 139 | then 140 | echo "Path not specified to find_maven_basedir" 141 | return 1 142 | fi 143 | 144 | basedir="$1" 145 | wdir="$1" 146 | while [ "$wdir" != '/' ] ; do 147 | if [ -d "$wdir"/.mvn ] ; then 148 | basedir=$wdir 149 | break 150 | fi 151 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 152 | if [ -d "${wdir}" ]; then 153 | wdir=$(cd "$wdir/.." || exit 1; pwd) 154 | fi 155 | # end of workaround 156 | done 157 | printf '%s' "$(cd "$basedir" || exit 1; pwd)" 158 | } 159 | 160 | # concatenates all lines of a file 161 | concat_lines() { 162 | if [ -f "$1" ]; then 163 | # Remove \r in case we run on Windows within Git Bash 164 | # and check out the repository with auto CRLF management 165 | # enabled. Otherwise, we may read lines that are delimited with 166 | # \r\n and produce $'-Xarg\r' rather than -Xarg due to word 167 | # splitting rules. 168 | tr -s '\r\n' ' ' < "$1" 169 | fi 170 | } 171 | 172 | log() { 173 | if [ "$MVNW_VERBOSE" = true ]; then 174 | printf '%s\n' "$1" 175 | fi 176 | } 177 | 178 | BASE_DIR=$(find_maven_basedir "$(dirname "$0")") 179 | if [ -z "$BASE_DIR" ]; then 180 | exit 1; 181 | fi 182 | 183 | MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR 184 | log "$MAVEN_PROJECTBASEDIR" 185 | 186 | ########################################################################################## 187 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 188 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 189 | ########################################################################################## 190 | wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" 191 | if [ -r "$wrapperJarPath" ]; then 192 | log "Found $wrapperJarPath" 193 | else 194 | log "Couldn't find $wrapperJarPath, downloading it ..." 195 | 196 | if [ -n "$MVNW_REPOURL" ]; then 197 | wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" 198 | else 199 | wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" 200 | fi 201 | while IFS="=" read -r key value; do 202 | # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) 203 | safeValue=$(echo "$value" | tr -d '\r') 204 | case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;; 205 | esac 206 | done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" 207 | log "Downloading from: $wrapperUrl" 208 | 209 | if $cygwin; then 210 | wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") 211 | fi 212 | 213 | if command -v wget > /dev/null; then 214 | log "Found wget ... using wget" 215 | [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" 216 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 217 | wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 218 | else 219 | wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" 220 | fi 221 | elif command -v curl > /dev/null; then 222 | log "Found curl ... using curl" 223 | [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" 224 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 225 | curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" 226 | else 227 | curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" 228 | fi 229 | else 230 | log "Falling back to using Java to download" 231 | javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" 232 | javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" 233 | # For Cygwin, switch paths to Windows format before running javac 234 | if $cygwin; then 235 | javaSource=$(cygpath --path --windows "$javaSource") 236 | javaClass=$(cygpath --path --windows "$javaClass") 237 | fi 238 | if [ -e "$javaSource" ]; then 239 | if [ ! -e "$javaClass" ]; then 240 | log " - Compiling MavenWrapperDownloader.java ..." 241 | ("$JAVA_HOME/bin/javac" "$javaSource") 242 | fi 243 | if [ -e "$javaClass" ]; then 244 | log " - Running MavenWrapperDownloader.java ..." 245 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" 246 | fi 247 | fi 248 | fi 249 | fi 250 | ########################################################################################## 251 | # End of extension 252 | ########################################################################################## 253 | 254 | # If specified, validate the SHA-256 sum of the Maven wrapper jar file 255 | wrapperSha256Sum="" 256 | while IFS="=" read -r key value; do 257 | case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;; 258 | esac 259 | done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" 260 | if [ -n "$wrapperSha256Sum" ]; then 261 | wrapperSha256Result=false 262 | if command -v sha256sum > /dev/null; then 263 | if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then 264 | wrapperSha256Result=true 265 | fi 266 | elif command -v shasum > /dev/null; then 267 | if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then 268 | wrapperSha256Result=true 269 | fi 270 | else 271 | echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." 272 | echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." 273 | exit 1 274 | fi 275 | if [ $wrapperSha256Result = false ]; then 276 | echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 277 | echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 278 | echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 279 | exit 1 280 | fi 281 | fi 282 | 283 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 284 | 285 | # For Cygwin, switch paths to Windows format before running java 286 | if $cygwin; then 287 | [ -n "$JAVA_HOME" ] && 288 | JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") 289 | [ -n "$CLASSPATH" ] && 290 | CLASSPATH=$(cygpath --path --windows "$CLASSPATH") 291 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 292 | MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") 293 | fi 294 | 295 | # Provide a "standardized" way to retrieve the CLI args that will 296 | # work with both Windows and non-Windows executions. 297 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" 298 | export MAVEN_CMD_LINE_ARGS 299 | 300 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 301 | 302 | # shellcheck disable=SC2086 # safe args 303 | exec "$JAVACMD" \ 304 | $MAVEN_OPTS \ 305 | $MAVEN_DEBUG_OPTS \ 306 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 307 | "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 308 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 309 | --------------------------------------------------------------------------------