feat(auth): implementar autenticação e autorização JWT
- Adiciona dependências do Spring Security e JWT (API, Impl, Jackson). - Configura o pipeline de segurança com autenticação stateless e filtros JWT. - Implementa serviços para geração e validação de tokens de acesso e refresh. - Cria endpoints para login (/api/auth/login) e refresh de token (/api/auth/refresh). - Move o endpoint de criação de usuário para /api/auth/signup e o protege. - Criptografa senhas dos usuários utilizando BCrypt antes de salvar. - Atualiza Postman Collection com requisições de autenticação e variáveis de ambiente. - Estende a interface UserDetails para o modelo Users. - Ajusta tamanho da coluna 'password' na tabela de usuários para hashes. - Adiciona um usuário padrão inicial com senha hash.master
parent
81499374b6
commit
41059bdfc3
|
|
@ -30,11 +30,15 @@ dependencies {
|
|||
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-validation'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-webmvc'
|
||||
implementation 'org.springframework.boot:spring-boot-starter-security'
|
||||
implementation 'io.jsonwebtoken:jjwt-api:0.12.6'
|
||||
implementation 'org.mapstruct:mapstruct:1.6.3'
|
||||
compileOnly 'org.projectlombok:lombok'
|
||||
developmentOnly 'org.springframework.boot:spring-boot-devtools'
|
||||
runtimeOnly 'com.h2database:h2'
|
||||
runtimeOnly 'org.postgresql:postgresql'
|
||||
runtimeOnly 'io.jsonwebtoken:jjwt-impl:0.12.6'
|
||||
runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.12.6'
|
||||
annotationProcessor 'org.projectlombok:lombok'
|
||||
annotationProcessor 'org.mapstruct:mapstruct-processor:1.6.3'
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-data-jdbc-test'
|
||||
|
|
|
|||
|
|
@ -6,10 +6,10 @@
|
|||
},
|
||||
"item": [
|
||||
{
|
||||
"name": "Users",
|
||||
"name": "Auth",
|
||||
"item": [
|
||||
{
|
||||
"name": "Create User",
|
||||
"name": "Login",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [
|
||||
|
|
@ -18,82 +18,114 @@
|
|||
"value": "application/json"
|
||||
}
|
||||
],
|
||||
"body": {
|
||||
"mode": "raw",
|
||||
"raw": "{\n \"username\": \"{{login_username}}\",\n \"password\": \"{{login_password}}\"\n}"
|
||||
},
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/auth/login",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"auth",
|
||||
"login"
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": [],
|
||||
"event": [
|
||||
{
|
||||
"listen": "test",
|
||||
"script": {
|
||||
"exec": [
|
||||
"pm.environment.set(\"access_token\", pm.cookies.get('access_token') || \"\");",
|
||||
"pm.environment.set(\"refresh_token\", pm.cookies.get('refresh_token') || \"\");"
|
||||
],
|
||||
"type": "text/javascript"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Refresh Token",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/auth/refresh",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"auth",
|
||||
"refresh"
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": [],
|
||||
"event": [
|
||||
{
|
||||
"listen": "test",
|
||||
"script": {
|
||||
"exec": [
|
||||
"pm.environment.set(\"access_token\", pm.cookies.get('access_token') || \"\");",
|
||||
"pm.environment.set(\"refresh_token\", pm.cookies.get('refresh_token') || \"\");"
|
||||
],
|
||||
"type": "text/javascript"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Signup (autenticado)",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [
|
||||
{
|
||||
"key": "Content-Type",
|
||||
"value": "application/json"
|
||||
},
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"body": {
|
||||
"mode": "raw",
|
||||
"raw": "{\n \"firstName\": \"João\",\n \"lastName\": \"Silva\",\n \"email\": \"joao.silva@hittelco.com\",\n \"password\": \"senha123\"\n}"
|
||||
},
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/users",
|
||||
"raw": "{{base_url}}/api/auth/signup",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"users"
|
||||
"auth",
|
||||
"signup"
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": []
|
||||
},
|
||||
{
|
||||
"name": "Create User - Test 2",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [
|
||||
{
|
||||
"key": "Content-Type",
|
||||
"value": "application/json"
|
||||
}
|
||||
],
|
||||
"body": {
|
||||
"mode": "raw",
|
||||
"raw": "{\n \"firstName\": \"Maria\",\n \"lastName\": \"Santos\",\n \"email\": \"maria.santos@accesscommunications.com\",\n \"password\": \"senha456\"\n}"
|
||||
},
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/users",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"users"
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": []
|
||||
},
|
||||
{
|
||||
"name": "Create User - Invalid Domain",
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"header": [
|
||||
{
|
||||
"key": "Content-Type",
|
||||
"value": "application/json"
|
||||
}
|
||||
],
|
||||
"body": {
|
||||
"mode": "raw",
|
||||
"raw": "{\n \"firstName\": \"Carlos\",\n \"lastName\": \"Oliveira\",\n \"email\": \"carlos@gmail.com\",\n \"password\": \"senha789\"\n}"
|
||||
},
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/users",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
"path": [
|
||||
"api",
|
||||
"users"
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": []
|
||||
},
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "Users",
|
||||
"item": [
|
||||
{
|
||||
"name": "Get All Users",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [],
|
||||
"header": [
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/users",
|
||||
"host": [
|
||||
|
|
@ -111,7 +143,12 @@
|
|||
"name": "Get User by ID",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [],
|
||||
"header": [
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/users/{{user_id}}",
|
||||
"host": [
|
||||
|
|
@ -130,9 +167,14 @@
|
|||
"name": "Get User by Username",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [],
|
||||
"header": [
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/users/username/joao.silva@hittelco.com",
|
||||
"raw": "{{base_url}}/api/users/username/{{username}}",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
|
|
@ -140,7 +182,7 @@
|
|||
"api",
|
||||
"users",
|
||||
"username",
|
||||
"joao.silva@hittelco.com"
|
||||
"{{username}}"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
|
@ -150,9 +192,14 @@
|
|||
"name": "Get User by Email",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [],
|
||||
"header": [
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/users/email/maria.santos@accesscommunications.com",
|
||||
"raw": "{{base_url}}/api/users/email/{{email}}",
|
||||
"host": [
|
||||
"{{base_url}}"
|
||||
],
|
||||
|
|
@ -160,7 +207,7 @@
|
|||
"api",
|
||||
"users",
|
||||
"email",
|
||||
"maria.santos@accesscommunications.com"
|
||||
"{{email}}"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
|
@ -174,6 +221,10 @@
|
|||
{
|
||||
"key": "Content-Type",
|
||||
"value": "application/json"
|
||||
},
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"body": {
|
||||
|
|
@ -198,7 +249,12 @@
|
|||
"name": "Delete User",
|
||||
"request": {
|
||||
"method": "DELETE",
|
||||
"header": [],
|
||||
"header": [
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/users/{{user_id}}",
|
||||
"host": [
|
||||
|
|
@ -226,6 +282,10 @@
|
|||
{
|
||||
"key": "Content-Type",
|
||||
"value": "application/json"
|
||||
},
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"body": {
|
||||
|
|
@ -253,6 +313,10 @@
|
|||
{
|
||||
"key": "Content-Type",
|
||||
"value": "application/json"
|
||||
},
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"body": {
|
||||
|
|
@ -276,7 +340,12 @@
|
|||
"name": "Get All Servers",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [],
|
||||
"header": [
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/servers",
|
||||
"host": [
|
||||
|
|
@ -294,7 +363,12 @@
|
|||
"name": "Get Server by ID",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [],
|
||||
"header": [
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/servers/{{server_id}}",
|
||||
"host": [
|
||||
|
|
@ -313,7 +387,12 @@
|
|||
"name": "Get Server by Name",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [],
|
||||
"header": [
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/servers/name/Production DB Server",
|
||||
"host": [
|
||||
|
|
@ -333,7 +412,12 @@
|
|||
"name": "Get Servers by Type",
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"header": [],
|
||||
"header": [
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/servers/type/PRODUCTION",
|
||||
"host": [
|
||||
|
|
@ -377,6 +461,10 @@
|
|||
{
|
||||
"key": "Content-Type",
|
||||
"value": "application/json"
|
||||
},
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"body": {
|
||||
|
|
@ -401,7 +489,12 @@
|
|||
"name": "Delete Server",
|
||||
"request": {
|
||||
"method": "DELETE",
|
||||
"header": [],
|
||||
"header": [
|
||||
{
|
||||
"key": "Authorization",
|
||||
"value": "Bearer {{access_token}}"
|
||||
}
|
||||
],
|
||||
"url": {
|
||||
"raw": "{{base_url}}/api/servers/{{server_id}}",
|
||||
"host": [
|
||||
|
|
@ -425,11 +518,41 @@
|
|||
"value": "http://localhost:8080",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"key": "login_username",
|
||||
"value": "joao.silva@hittelco.com",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"key": "login_password",
|
||||
"value": "senha123",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"key": "username",
|
||||
"value": "",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"key": "email",
|
||||
"value": "",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"key": "user_id",
|
||||
"value": "",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"key": "access_token",
|
||||
"value": "",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"key": "refresh_token",
|
||||
"value": "",
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"key": "server_id",
|
||||
"value": "",
|
||||
|
|
@ -437,4 +560,3 @@
|
|||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,23 @@
|
|||
package com.hitcommunications.servermanager.config.security;
|
||||
|
||||
import com.hitcommunications.servermanager.repositories.UsersRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class CustomUserDetailsService implements UserDetailsService {
|
||||
|
||||
private final UsersRepository usersRepository;
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
return usersRepository.findByUsername(username)
|
||||
.or(() -> usersRepository.findByEmail(username))
|
||||
.map(UserPrincipal::fromUser)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
package com.hitcommunications.servermanager.config.security;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Arrays;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
public static final String ACCESS_TOKEN_COOKIE = "access_token";
|
||||
|
||||
private final JwtService jwtService;
|
||||
private final UserDetailsService userDetailsService;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
@NonNull HttpServletRequest request,
|
||||
@NonNull HttpServletResponse response,
|
||||
@NonNull FilterChain filterChain
|
||||
) throws ServletException, IOException {
|
||||
|
||||
final String jwt = resolveToken(request);
|
||||
try {
|
||||
if (jwt != null && SecurityContextHolder.getContext().getAuthentication() == null
|
||||
&& JwtService.TokenType.ACCESS == jwtService.extractTokenType(jwt)) {
|
||||
String username = jwtService.extractUsername(jwt);
|
||||
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
|
||||
if (jwtService.isTokenValid(jwt, userDetails, JwtService.TokenType.ACCESS)) {
|
||||
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(
|
||||
userDetails,
|
||||
null,
|
||||
userDetails.getAuthorities()
|
||||
);
|
||||
authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
|
||||
SecurityContextHolder.getContext().setAuthentication(authToken);
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// Let the security chain handle unauthorized requests
|
||||
}
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private String resolveToken(HttpServletRequest request) {
|
||||
String authHeader = request.getHeader("Authorization");
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
return authHeader.substring(7);
|
||||
}
|
||||
|
||||
Cookie[] cookies = request.getCookies();
|
||||
if (cookies == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Arrays.stream(cookies)
|
||||
.filter(cookie -> ACCESS_TOKEN_COOKIE.equals(cookie.getName()))
|
||||
.findFirst()
|
||||
.map(Cookie::getValue)
|
||||
.orElse(null);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package com.hitcommunications.servermanager.config.security;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@Data
|
||||
@ConfigurationProperties(prefix = "security.jwt")
|
||||
public class JwtProperties {
|
||||
/**
|
||||
* Secret key used to sign the JWTs.
|
||||
*/
|
||||
private String secret;
|
||||
|
||||
/**
|
||||
* Access token validity window.
|
||||
*/
|
||||
private Duration accessTokenExpiration;
|
||||
|
||||
/**
|
||||
* Refresh token validity window.
|
||||
*/
|
||||
private Duration refreshTokenExpiration;
|
||||
}
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
package com.hitcommunications.servermanager.config.security;
|
||||
|
||||
import io.jsonwebtoken.Claims;
|
||||
import io.jsonwebtoken.Jwts;
|
||||
import io.jsonwebtoken.SignatureAlgorithm;
|
||||
import io.jsonwebtoken.security.Keys;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Collections;
|
||||
import java.util.Date;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class JwtService {
|
||||
|
||||
public static final String TOKEN_TYPE_CLAIM = "token_type";
|
||||
|
||||
private final JwtProperties properties;
|
||||
|
||||
public String generateAccessToken(UserDetails userDetails) {
|
||||
return buildToken(Collections.singletonMap(TOKEN_TYPE_CLAIM, TokenType.ACCESS.name()), userDetails, properties.getAccessTokenExpiration());
|
||||
}
|
||||
|
||||
public String generateRefreshToken(UserDetails userDetails) {
|
||||
return buildToken(Collections.singletonMap(TOKEN_TYPE_CLAIM, TokenType.REFRESH.name()), userDetails, properties.getRefreshTokenExpiration());
|
||||
}
|
||||
|
||||
public String extractUsername(String token) {
|
||||
return extractClaim(token, Claims::getSubject);
|
||||
}
|
||||
|
||||
public TokenType extractTokenType(String token) {
|
||||
String tokenType = extractClaim(token, claims -> claims.get(TOKEN_TYPE_CLAIM, String.class));
|
||||
try {
|
||||
return tokenType == null ? null : TokenType.valueOf(tokenType);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isTokenValid(String token, UserDetails userDetails) {
|
||||
final String username = extractUsername(token);
|
||||
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
|
||||
}
|
||||
|
||||
public boolean isTokenValid(String token, UserDetails userDetails, TokenType expectedType) {
|
||||
final String username = extractUsername(token);
|
||||
TokenType tokenType = extractTokenType(token);
|
||||
return username.equals(userDetails.getUsername()) && expectedType == tokenType && !isTokenExpired(token);
|
||||
}
|
||||
|
||||
private boolean isTokenExpired(String token) {
|
||||
return extractExpiration(token).before(new Date());
|
||||
}
|
||||
|
||||
private Date extractExpiration(String token) {
|
||||
return extractClaim(token, Claims::getExpiration);
|
||||
}
|
||||
|
||||
private <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
|
||||
final Claims claims = extractAllClaims(token);
|
||||
return claimsResolver.apply(claims);
|
||||
}
|
||||
|
||||
private Claims extractAllClaims(String token) {
|
||||
return Jwts.parser()
|
||||
.verifyWith(getSignInKey())
|
||||
.build()
|
||||
.parseSignedClaims(token)
|
||||
.getPayload();
|
||||
}
|
||||
|
||||
private String buildToken(Map<String, Object> extraClaims, UserDetails userDetails, Duration expiration) {
|
||||
Instant now = Instant.now();
|
||||
Instant expiry = now.plus(expiration.toMillis(), ChronoUnit.MILLIS);
|
||||
|
||||
return Jwts.builder()
|
||||
.claims(extraClaims)
|
||||
.subject(userDetails.getUsername())
|
||||
.issuedAt(Date.from(now))
|
||||
.expiration(Date.from(expiry))
|
||||
.signWith(getSignInKey(), SignatureAlgorithm.HS256)
|
||||
.compact();
|
||||
}
|
||||
|
||||
private SecretKey getSignInKey() {
|
||||
byte[] keyBytes = properties.getSecret().getBytes(StandardCharsets.UTF_8);
|
||||
return Keys.hmacShaKeyFor(keyBytes);
|
||||
}
|
||||
|
||||
public enum TokenType {
|
||||
ACCESS,
|
||||
REFRESH
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
package com.hitcommunications.servermanager.config.security;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@EnableConfigurationProperties(JwtProperties.class)
|
||||
@RequiredArgsConstructor
|
||||
public class SecurityConfig {
|
||||
|
||||
private final JwtAuthenticationFilter jwtAuthFilter;
|
||||
private final UserDetailsService userDetailsService;
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/", "/api/auth/login", "/api/auth/refresh").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.authenticationProvider(authenticationProvider())
|
||||
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.httpBasic(Customizer.withDefaults());
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationProvider authenticationProvider() {
|
||||
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(userDetailsService);
|
||||
authProvider.setPasswordEncoder(passwordEncoder());
|
||||
return authProvider;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
|
||||
return config.getAuthenticationManager();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
package com.hitcommunications.servermanager.config.security;
|
||||
|
||||
import com.hitcommunications.servermanager.model.Users;
|
||||
import lombok.Getter;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Getter
|
||||
public class UserPrincipal implements UserDetails {
|
||||
|
||||
private final UUID id;
|
||||
private final String username;
|
||||
private final String password;
|
||||
private final Collection<? extends GrantedAuthority> authorities;
|
||||
|
||||
private UserPrincipal(UUID id, String username, String password, Collection<? extends GrantedAuthority> authorities) {
|
||||
this.id = id;
|
||||
this.username = username;
|
||||
this.password = password;
|
||||
this.authorities = authorities;
|
||||
}
|
||||
|
||||
public static UserPrincipal fromUser(Users user) {
|
||||
return new UserPrincipal(
|
||||
user.getId(),
|
||||
user.getUsername(),
|
||||
user.getPassword(),
|
||||
List.of(new SimpleGrantedAuthority("ROLE_USER"))
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
package com.hitcommunications.servermanager.controllers;
|
||||
|
||||
import com.hitcommunications.servermanager.config.security.JwtAuthenticationFilter;
|
||||
import com.hitcommunications.servermanager.config.security.JwtProperties;
|
||||
import com.hitcommunications.servermanager.model.dtos.AuthResponse;
|
||||
import com.hitcommunications.servermanager.model.dtos.AuthTokens;
|
||||
import com.hitcommunications.servermanager.model.dtos.LoginRequest;
|
||||
import com.hitcommunications.servermanager.model.dtos.NewUserDTO;
|
||||
import com.hitcommunications.servermanager.model.dtos.UserDTO;
|
||||
import com.hitcommunications.servermanager.services.AuthService;
|
||||
import com.hitcommunications.servermanager.utils.CookieUtils;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseCookie;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/auth")
|
||||
@RequiredArgsConstructor
|
||||
public class AuthController {
|
||||
|
||||
public static final String REFRESH_TOKEN_COOKIE = "refresh_token";
|
||||
|
||||
private final AuthService authService;
|
||||
private final JwtProperties jwtProperties;
|
||||
|
||||
@PostMapping("/login")
|
||||
public ResponseEntity<AuthResponse> login(@RequestBody @Valid LoginRequest request, HttpServletRequest httpRequest) {
|
||||
AuthTokens tokens = authService.login(request);
|
||||
return buildResponse(tokens, httpRequest);
|
||||
}
|
||||
|
||||
@PostMapping("/refresh")
|
||||
public ResponseEntity<AuthResponse> refresh(HttpServletRequest request) {
|
||||
String refreshToken = CookieUtils.getCookieValue(request, REFRESH_TOKEN_COOKIE);
|
||||
AuthTokens tokens = authService.refresh(refreshToken);
|
||||
return buildResponse(tokens, request);
|
||||
}
|
||||
|
||||
@PostMapping("/signup")
|
||||
public ResponseEntity<UserDTO> signup(@RequestBody @Valid NewUserDTO request) throws IllegalAccessException {
|
||||
UserDTO user = authService.signup(request);
|
||||
return ResponseEntity.ok(user);
|
||||
}
|
||||
|
||||
private ResponseEntity<AuthResponse> buildResponse(AuthTokens tokens, HttpServletRequest request) {
|
||||
boolean secure = request.isSecure();
|
||||
ResponseCookie accessCookie = CookieUtils.buildCookie(
|
||||
JwtAuthenticationFilter.ACCESS_TOKEN_COOKIE,
|
||||
tokens.accessToken(),
|
||||
jwtProperties.getAccessTokenExpiration(),
|
||||
false,
|
||||
secure
|
||||
);
|
||||
|
||||
ResponseCookie refreshCookie = CookieUtils.buildCookie(
|
||||
REFRESH_TOKEN_COOKIE,
|
||||
tokens.refreshToken(),
|
||||
jwtProperties.getRefreshTokenExpiration(),
|
||||
true,
|
||||
secure
|
||||
);
|
||||
|
||||
return ResponseEntity.ok()
|
||||
.header(HttpHeaders.SET_COOKIE, accessCookie.toString(), refreshCookie.toString())
|
||||
.body(new AuthResponse(tokens.user()));
|
||||
}
|
||||
}
|
||||
|
|
@ -18,11 +18,6 @@ public class UsersController {
|
|||
|
||||
private final UsersService usersService;
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity<UserDTO> create(@RequestBody @Valid NewUserDTO crateDTO) throws IllegalAccessException {
|
||||
return ResponseEntity.ok().body(usersService.create(crateDTO));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<UserDTO> getById(@PathVariable UUID id) {
|
||||
return ResponseEntity.ok().body(usersService.getById(id));
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ public class Users {
|
|||
@Column(nullable = false, unique = true, length = 100)
|
||||
private String email;
|
||||
|
||||
@Column(nullable = false, length = 20)
|
||||
@Column(nullable = false, length = 120)
|
||||
private String password;
|
||||
|
||||
@Column(nullable = false, length = 30)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,6 @@
|
|||
package com.hitcommunications.servermanager.model.dtos;
|
||||
|
||||
public record AuthResponse(
|
||||
UserDTO user
|
||||
) {
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
package com.hitcommunications.servermanager.model.dtos;
|
||||
|
||||
public record AuthTokens(
|
||||
String accessToken,
|
||||
String refreshToken,
|
||||
UserDTO user
|
||||
) {
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
package com.hitcommunications.servermanager.model.dtos;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record LoginRequest(
|
||||
@NotBlank String username,
|
||||
@NotBlank String password
|
||||
) {
|
||||
}
|
||||
|
|
@ -0,0 +1,88 @@
|
|||
package com.hitcommunications.servermanager.services;
|
||||
|
||||
import com.hitcommunications.servermanager.config.security.JwtService;
|
||||
import com.hitcommunications.servermanager.config.security.UserPrincipal;
|
||||
import com.hitcommunications.servermanager.model.Users;
|
||||
import com.hitcommunications.servermanager.model.dtos.AuthTokens;
|
||||
import com.hitcommunications.servermanager.model.dtos.LoginRequest;
|
||||
import com.hitcommunications.servermanager.model.dtos.NewUserDTO;
|
||||
import com.hitcommunications.servermanager.model.dtos.UserDTO;
|
||||
import com.hitcommunications.servermanager.mappers.UsersMapper;
|
||||
import com.hitcommunications.servermanager.repositories.UsersRepository;
|
||||
import jakarta.transaction.Transactional;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AuthService {
|
||||
|
||||
private final AuthenticationManager authenticationManager;
|
||||
private final UsersService usersService;
|
||||
private final UsersRepository usersRepository;
|
||||
private final UsersMapper usersMapper;
|
||||
private final JwtService jwtService;
|
||||
private final UserDetailsService userDetailsService;
|
||||
|
||||
public AuthTokens login(LoginRequest request) {
|
||||
Authentication authentication = authenticationManager.authenticate(
|
||||
new UsernamePasswordAuthenticationToken(request.username(), request.password())
|
||||
);
|
||||
|
||||
UserPrincipal principal = (UserPrincipal) authentication.getPrincipal();
|
||||
Users user = usersRepository.findById(principal.getId())
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found after authentication."));
|
||||
|
||||
updateLastLogin(user);
|
||||
return issueTokens(user, principal);
|
||||
}
|
||||
|
||||
public AuthTokens refresh(String refreshToken) {
|
||||
if (refreshToken == null || refreshToken.isBlank()) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Refresh token is missing.");
|
||||
}
|
||||
|
||||
try {
|
||||
String username = jwtService.extractUsername(refreshToken);
|
||||
var userDetails = userDetailsService.loadUserByUsername(username);
|
||||
if (!jwtService.isTokenValid(refreshToken, userDetails, JwtService.TokenType.REFRESH)) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid refresh token.");
|
||||
}
|
||||
|
||||
Users user = usersRepository.findByUsername(username)
|
||||
.or(() -> usersRepository.findByEmail(username))
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found for refresh token."));
|
||||
|
||||
return issueTokens(user, UserPrincipal.fromUser(user));
|
||||
} catch (ResponseStatusException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid refresh token.");
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserDTO signup(NewUserDTO createDTO) throws IllegalAccessException {
|
||||
return usersService.create(createDTO);
|
||||
}
|
||||
|
||||
private AuthTokens issueTokens(Users user, UserPrincipal principal) {
|
||||
String accessToken = jwtService.generateAccessToken(principal);
|
||||
String refreshToken = jwtService.generateRefreshToken(principal);
|
||||
return new AuthTokens(accessToken, refreshToken, usersMapper.toDTO(user));
|
||||
}
|
||||
|
||||
private void updateLastLogin(Users user) {
|
||||
user.setLastLogin(Timestamp.from(Instant.now()));
|
||||
usersRepository.save(user);
|
||||
}
|
||||
}
|
||||
|
|
@ -7,6 +7,7 @@ import com.hitcommunications.servermanager.model.dtos.UserDTO;
|
|||
import com.hitcommunications.servermanager.repositories.UsersRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
|
@ -17,6 +18,7 @@ import java.util.UUID;
|
|||
public class UsersService {
|
||||
private final UsersMapper mapper;
|
||||
private final UsersRepository repo;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
|
||||
private final String ALLOWED_DOMAIN = Arrays.asList("hittelco.com", "accesscommunications.com").toString();
|
||||
|
||||
|
|
@ -31,6 +33,7 @@ public class UsersService {
|
|||
});
|
||||
|
||||
Users entity = mapper.toEntity(createDTO);
|
||||
entity.setPassword(passwordEncoder.encode(createDTO.password()));
|
||||
entity = repo.save(entity);
|
||||
return mapper.toDTO(entity);
|
||||
}
|
||||
|
|
@ -77,6 +80,7 @@ public class UsersService {
|
|||
});
|
||||
|
||||
mapper.partialUpdate(updateDTO, entity);
|
||||
entity.setPassword(passwordEncoder.encode(updateDTO.password()));
|
||||
entity = repo.save(entity);
|
||||
return mapper.toDTO(entity);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,37 @@
|
|||
package com.hitcommunications.servermanager.utils;
|
||||
|
||||
import jakarta.servlet.http.Cookie;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.springframework.http.ResponseCookie;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.Optional;
|
||||
|
||||
public final class CookieUtils {
|
||||
|
||||
private CookieUtils() {
|
||||
}
|
||||
|
||||
public static String getCookieValue(HttpServletRequest request, String name) {
|
||||
if (request.getCookies() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
Optional<Cookie> cookie = Arrays.stream(request.getCookies())
|
||||
.filter(c -> name.equals(c.getName()))
|
||||
.findFirst();
|
||||
|
||||
return cookie.map(Cookie::getValue).orElse(null);
|
||||
}
|
||||
|
||||
public static ResponseCookie buildCookie(String name, String value, Duration maxAge, boolean httpOnly, boolean secure) {
|
||||
return ResponseCookie.from(name, value)
|
||||
.httpOnly(httpOnly)
|
||||
.secure(secure)
|
||||
.path("/")
|
||||
.sameSite("Lax")
|
||||
.maxAge(maxAge)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
|
@ -22,3 +22,9 @@ spring:
|
|||
dialect: org.hibernate.dialect.PostgreSQLDialect
|
||||
format_sql: true
|
||||
default_schema: server-manager
|
||||
|
||||
security:
|
||||
jwt:
|
||||
secret: ${JWT_SECRET:change-me-change-me-change-me-change-me-change-me}
|
||||
access-token-expiration: PT30M
|
||||
refresh-token-expiration: P30D
|
||||
|
|
|
|||
|
|
@ -0,0 +1,20 @@
|
|||
INSERT INTO "server-manager".tab_users (
|
||||
id,
|
||||
username,
|
||||
email,
|
||||
password,
|
||||
first_name,
|
||||
last_name,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
'00000000-0000-0000-0000-000000000001',
|
||||
'default',
|
||||
'default@hittelco.com',
|
||||
'$2b$10$4hvMSZp/AC0k9HXqxtdO2e0KUQReRgcnJEcY5gWYTPiDMgu2D4bSK',
|
||||
'Default',
|
||||
'User',
|
||||
CURRENT_TIMESTAMP,
|
||||
CURRENT_TIMESTAMP
|
||||
)
|
||||
ON CONFLICT DO NOTHING;
|
||||
Loading…
Reference in New Issue