Revert "????????"

This reverts commit bc1e598987.
This commit is contained in:
2025-12-28 22:10:13 +01:00
parent bc1e598987
commit f7630b6754
18 changed files with 507 additions and 67 deletions

View File

@@ -3,6 +3,7 @@ package be.naaturel.boardmateapi;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BoardmateApiApplication {

View File

@@ -0,0 +1,44 @@
package be.naaturel.boardmateapi.common.models;
public class Client {
private String id;
private String name;
private String username;
private String key;
public Client(String id, String name, String username, String key){
this.id = id;
this.name = name;
this.username = username;
this.key = key;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}

View File

@@ -1,18 +1,30 @@
package be.naaturel.boardmateapi.configurations.configurations;
import be.naaturel.boardmateapi.configurations.properties.AppProperties;
import com.nimbusds.jose.jwk.source.ImmutableSecret;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
@Configuration
@@ -28,10 +40,29 @@ public class AppSecurityConfig {
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) {
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
SecurityFilterChain filterChain(HttpSecurity http, @Autowired JwtDecoder jwtDecoder) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers(
"/health",
"/actuator/**",
"/v3/api-docs/**",
"/v3/api-docs/swagger-config",
"/webjars/**",
"/swagger-ui/**",
"/docs/**",
"/v1/docs/**",
"/swagger-ui.html",
"/authenticate",
"/client/create").permitAll()
.anyRequest().authenticated()
).oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
.build();
}

View File

@@ -0,0 +1,49 @@
package be.naaturel.boardmateapi.configurations.configurations;
import be.naaturel.boardmateapi.configurations.properties.AppProperties;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.KeyUse;
import com.nimbusds.jose.jwk.OctetSequenceKey;
import com.nimbusds.jose.jwk.source.ImmutableSecret;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
@Configuration
public class JWTConfig {
private final AppProperties conf;
@Autowired
public JWTConfig(AppProperties appConf) {
this.conf = appConf;
}
@Bean
public JwtEncoder jwtEncoder() {
byte[] keyBytes = Base64.getDecoder().decode(conf.jwtSecret);
SecretKey key = new SecretKeySpec(keyBytes, "HmacSHA256");
return new NimbusJwtEncoder(new ImmutableSecret<>(key));
}
@Bean
public JwtDecoder jwtDecoder() {
byte[] keyBytes = Base64.getDecoder().decode(conf.jwtSecret);
SecretKey key = new SecretKeySpec(keyBytes, "HmacSHA256");
return NimbusJwtDecoder.withSecretKey(key).build();
}
}

View File

@@ -1,8 +1,29 @@
package be.naaturel.boardmateapi.configurations.configurations;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SwaggerConfig {
@Bean
public OpenAPI customOpenAPI() {
final String securitySchemeName = "bearerAuth";
return new OpenAPI()
.addSecurityItem(new SecurityRequirement().addList(securitySchemeName))
.components(
new Components()
.addSecuritySchemes(securitySchemeName,
new SecurityScheme()
.name(securitySchemeName)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")
)
);
}
}

View File

@@ -21,4 +21,6 @@ public class AppProperties {
@Value("${spring.mongodb.database}")
public String database;
@Value("${jwt.secret}")
public String jwtSecret;
}

View File

@@ -0,0 +1,80 @@
package be.naaturel.boardmateapi.controllers;
import be.naaturel.boardmateapi.common.models.Client;
import be.naaturel.boardmateapi.controllers.dtos.*;
import be.naaturel.boardmateapi.services.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.time.Instant;
@RestController
public class AuthController {
private final ClientService service;
private final JwtEncoder jwtEncoder;
@Autowired
public AuthController(ClientService service, JwtEncoder jwtEncoder) {
this.service = service;
this.jwtEncoder = jwtEncoder;
}
@PostMapping("/authenticate")
public ResponseEntity<ResponseBody<AuthResponseDto>> login(@RequestBody AuthRequestDto request) {
ResponseBody<AuthResponseDto> result = ResponseBody.createEmpty();
try {
Client user = service.authenticate(
request.getUsername(),
request.getKey()
);
Instant now = Instant.now();
JwtClaimsSet claims = JwtClaimsSet.builder()
.subject(user.getId())
.claim("name", user.getName())
.claim("username", user.getUsername())
.issuedAt(now)
.expiresAt(now.plusSeconds(3600*12))
.build();
JwtEncoderParameters params =
JwtEncoderParameters.from(
JwsHeader.with(MacAlgorithm.HS256).build(),
claims
);
String token = jwtEncoder.encode(params).getTokenValue();
AuthResponseDto response = new AuthResponseDto();
response.setName(user.getName());
response.setUsername(user.getUsername());
response.setClientId(user.getId());
response.setAuthToken(token);
result.setSuccess(true);
result.setData(response);
return ResponseEntity
.status(HttpStatus.OK)
.body(result);
} catch (Exception e){
e.printStackTrace();
result.setMessage(e.getMessage());
return ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(result);
}
}
}

View File

@@ -0,0 +1,42 @@
package be.naaturel.boardmateapi.controllers;
import be.naaturel.boardmateapi.controllers.dtos.AuthRequestDto;
import be.naaturel.boardmateapi.controllers.dtos.AuthResponseDto;
import be.naaturel.boardmateapi.controllers.dtos.ClientDto;
import be.naaturel.boardmateapi.controllers.dtos.ResponseBody;
import be.naaturel.boardmateapi.services.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
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.RestController;
@RestController
public class ClientController {
private final ClientService service;
@Autowired
public ClientController(ClientService service){
this.service = service;
}
@PostMapping("/client/create")
public ResponseEntity<ResponseBody<String>> create(@RequestBody ClientDto dto) {
ResponseBody<String> result = ResponseBody.createEmpty();
try{
String clientId = service.create(dto.getName(), dto.getUsername(), dto.getKey());
result.setData(clientId);
return ResponseEntity.
status(HttpStatus.OK)
.body(result);
} catch (Exception e){
result.setMessage(e.getMessage());
return ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(result);
}
}
}

View File

@@ -0,0 +1,22 @@
package be.naaturel.boardmateapi.controllers.dtos;
public class AuthRequestDto {
private String username;
private String key;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}

View File

@@ -0,0 +1,40 @@
package be.naaturel.boardmateapi.controllers.dtos;
public class AuthResponseDto {
private String clientId;
private String name;
private String username;
private String authToken;
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthToken() {
return authToken;
}
public void setAuthToken(String authToken) {
this.authToken = authToken;
}
}

View File

@@ -0,0 +1,32 @@
package be.naaturel.boardmateapi.controllers.dtos;
public class ClientDto {
private String name;
private String username;
private String key;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}

View File

@@ -0,0 +1,11 @@
package be.naaturel.boardmateapi.repository;
import be.naaturel.boardmateapi.repository.dtos.ClientDto;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.Optional;
public interface ClientRepo extends MongoRepository<ClientDto, String> {
Optional<ClientDto> findByServiceUsername(String serviceUsername);
}

View File

@@ -0,0 +1,59 @@
package be.naaturel.boardmateapi.repository.dtos;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
@Document(collection = "clients")
public class ClientDto {
@Id
private String id;
@Field("name")
private String name;
@Field("clientId")
private String clientId;
@Field("serviceUsername")
private String serviceUsername;
@Field("serviceKey")
private String serviceKey;
public String getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getServiceUsername() {
return serviceUsername;
}
public void setServiceUsername(String serviceUsername) {
this.serviceUsername = serviceUsername;
}
public void setServiceKey(String serviceKey) {
this.serviceKey = serviceKey;
}
public String getServiceKey() {
return serviceKey;
}
}

View File

@@ -0,0 +1,56 @@
package be.naaturel.boardmateapi.services;
import be.naaturel.boardmateapi.common.exceptions.ServiceException;
import be.naaturel.boardmateapi.common.models.Client;
import be.naaturel.boardmateapi.repository.ClientRepo;
import be.naaturel.boardmateapi.repository.dtos.ClientDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.UUID;
import static java.util.UUID.randomUUID;
@Service
public class ClientService {
private final ClientRepo repo;
private final PasswordEncoder passwordEncoder;
@Autowired
public ClientService(ClientRepo repo, PasswordEncoder passwordEncoder){
this.repo = repo;
this.passwordEncoder = passwordEncoder;
}
public Client authenticate(String username, String key) throws ServiceException {
try {
ClientDto dto = repo.findByServiceUsername(username)
.orElseThrow(() -> new RuntimeException("Invalid username"));
if (passwordEncoder.matches(key, dto.getServiceKey())) {
return new Client(dto.getClientId(), dto.getName(), dto.getServiceUsername(), dto.getServiceKey());
} else {
throw new RuntimeException("Invalid username or password");
}
} catch (Exception e){
throw new ServiceException("Authentication failed", e);
}
}
public String create(String name, String username, String key) throws ServiceException {
try{
ClientDto dto = new ClientDto();
dto.setClientId(randomUUID().toString());
dto.setName(name);
dto.setServiceUsername(username);
String encodedKey = passwordEncoder.encode(key);
dto.setServiceKey(encodedKey);
ClientDto result = repo.save(dto);
return result.getClientId();
} catch (Exception e){
throw new ServiceException("Unable to create client", e);
}
}
}

View File

@@ -10,13 +10,20 @@ sec.cors.authorizedHots=*
sec.cors.authorizedMethods=GET,POST,PUT,DELETE,OPTION
sec.cors.authorizedHeader=Authorization,Content-type
jwt.secret=${JWT_SECRET}
jwt.expiration=3600
server.ssl.key-store=${SSL_KEYSTORE_PATH}
server.ssl.key-store-password=heplhepl
server.ssl.key-store-type=PKCS12
server.ssl.key-alias=board-mate-api
#=============MQTT=============
mqtt.broker-url=tcp://test.mosquitto.org:1883
mqtt.client-id=board-mate-client
mqtt.topic=board-mate-test/topic
mqtt.username=yourUsername
mqtt.password=yourPassword
#=============METRICS=============