Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 43 additions & 6 deletions MiniKms/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,12 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
Expand All @@ -55,11 +49,48 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.13.0</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.13.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.13.0</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.7.8</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.42</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.6.0</version>
</dependency>
</dependencies>

<build>
Expand All @@ -72,6 +103,12 @@
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.40</version>
</path>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.6.0</version>
</path>
</annotationProcessorPaths>
</configuration>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package ftn.security.minikms.config;

import com.fasterxml.jackson.databind.MapperFeature;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JsonDeserializationConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer caseInsensitiveEnums() {
return builder -> builder
.featuresToEnable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package ftn.security.minikms.config;

import ftn.security.minikms.service.auth.JwtAuthenticationFilter;
import ftn.security.minikms.service.auth.MiniKmsUserDetailsService;
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.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
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.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
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;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.List;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
private final String jwtSecret;
private final MiniKmsUserDetailsService service;

@Autowired
public SecurityConfig(
@Value("${jwt.secret}") String jwtSecret,
MiniKmsUserDetailsService service) {
this.jwtSecret = jwtSecret;
this.service = service;
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
// Stateless, token-only API: no cookies => CSRF not applicable
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.cors(Customizer.withDefaults())

.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.logout(AbstractHttpConfigurer::disable)

.authorizeHttpRequests(auth -> auth
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.requestMatchers("/api/v1/auth/**").permitAll()
.requestMatchers(HttpMethod.GET, "/api/v1/keys/**").authenticated() // Allow all roles to GET
.requestMatchers("/api/v1/keys/**").hasRole("MANAGER")
.anyRequest().authenticated()
)

.userDetailsService(service)
.addFilterBefore(new JwtAuthenticationFilter(
jwtSecret,
service
), UsernamePasswordAuthenticationFilter.class)
.build();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
return configuration.getAuthenticationManager();
}

@Bean
public CorsConfigurationSource corsConfigurationSource() {
var config = new CorsConfiguration();
config.setAllowedOrigins(List.of("http://localhost:4200", "http://localhost"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
config.setAllowCredentials(false);

var source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package ftn.security.minikms.controller;

import ftn.security.minikms.dto.AuthDTO;
import ftn.security.minikms.dto.TokenDTO;
import ftn.security.minikms.service.auth.JwtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
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/v1/auth")
public class AuthController {
private final AuthenticationManager authManager;
private final JwtService jwtService;

@Autowired
public AuthController(AuthenticationManager authManager, JwtService jwtService) {
this.authManager = authManager;
this.jwtService = jwtService;
}

@PostMapping
public ResponseEntity<?> auth(@RequestBody AuthDTO dto) {
try {
var auth = authManager.authenticate(
new UsernamePasswordAuthenticationToken(dto.getUsername(), dto.getPassword())
);
var token = jwtService.generateToken(auth.getName());
return ResponseEntity.ok(new TokenDTO(token));
} catch (AuthenticationException e) {
return ResponseEntity.status(401).body("Invalid credentials");
}
}
}
Original file line number Diff line number Diff line change
@@ -1,35 +1,64 @@
package ftn.security.minikms.controller;

import ftn.security.minikms.dto.KeyDTO;
import ftn.security.minikms.dto.KeyMapper;
import ftn.security.minikms.service.KeyService;
import org.mapstruct.factory.Mappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.security.GeneralSecurityException;
import java.security.InvalidParameterException;
import java.security.Principal;
import java.util.UUID;

@RestController
@RequestMapping(value = "/api/v1/keys")
public class KeyManagementController {
private final KeyService keyService;
private final KeyMapper mapper;

@Autowired
private KeyService keyService;
public KeyManagementController(KeyService keyService) {
this.keyService = keyService;
this.mapper = Mappers.getMapper(KeyMapper.class);
}

@PostMapping("/create")
public ResponseEntity<KeyDTO> createKey(@RequestBody KeyDTO dto) throws NoSuchAlgorithmException {
String id = keyService.createKey(dto.getKeyType());
dto.setId(id);
return new ResponseEntity<>(dto, HttpStatus.CREATED);
public ResponseEntity<?> createKey(@RequestBody KeyDTO dto, Principal principal) throws GeneralSecurityException {
var username = principal.getName();

try {
var created = keyService.createKey(dto.getAlias(), dto.getKeyType(), dto.getAllowedOperations(), username);
return ResponseEntity.status(HttpStatus.CREATED).body(mapper.toDto(created));
} catch (InvalidParameterException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}

@PostMapping("/rotate")
public ResponseEntity<KeyDTO> rotateKey(@RequestBody KeyDTO dto){
keyService.rotateKey(dto.getKeyType(), dto.getId());
return new ResponseEntity<>(dto, HttpStatus.CREATED);
}
@PutMapping("/delete/{id}")
public ResponseEntity<String> deleteKey(@PathVariable String id){
keyService.deleteKey(id);
return new ResponseEntity<>(id, HttpStatus.OK);
public ResponseEntity<?> rotateKey(@RequestBody KeyDTO dto, Principal principal) throws GeneralSecurityException {
var username = principal.getName();

try {
var created = keyService.rotateKey(dto.getId(), username);
return ResponseEntity.status(HttpStatus.CREATED).body(mapper.toDto(created));
} catch (InvalidParameterException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}

@DeleteMapping("/{id}")
public ResponseEntity<?> deleteKey(@PathVariable UUID id, Principal principal) {
var username = principal.getName();

try {
keyService.deleteKey(id, username);
return ResponseEntity.noContent().build();
} catch (InvalidParameterException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}
}
9 changes: 9 additions & 0 deletions MiniKms/src/main/java/ftn/security/minikms/dto/AuthDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package ftn.security.minikms.dto;

import lombok.Data;

@Data
public class AuthDTO {
private String username;
private String password;
}
19 changes: 10 additions & 9 deletions MiniKms/src/main/java/ftn/security/minikms/dto/KeyDTO.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
package ftn.security.minikms.dto;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import ftn.security.minikms.enumeration.KeyOperation;
import ftn.security.minikms.enumeration.KeyType;
import lombok.*;

@Getter
@Setter
import java.util.List;
import java.util.UUID;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class KeyDTO {
private String id;
private UUID id;
private String alias;
private String keyType;
private KeyType keyType;
private List<KeyOperation> allowedOperations;
}
9 changes: 9 additions & 0 deletions MiniKms/src/main/java/ftn/security/minikms/dto/KeyMapper.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package ftn.security.minikms.dto;

import ftn.security.minikms.entity.KeyMetadata;
import org.mapstruct.Mapper;

@Mapper
public interface KeyMapper {
KeyMetadataDTO toDto(KeyMetadata key);
}
21 changes: 21 additions & 0 deletions MiniKms/src/main/java/ftn/security/minikms/dto/KeyMetadataDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package ftn.security.minikms.dto;

import ftn.security.minikms.enumeration.KeyOperation;
import ftn.security.minikms.enumeration.KeyType;
import lombok.*;

import java.time.Instant;
import java.util.List;
import java.util.UUID;

@Data
@NoArgsConstructor
public class KeyMetadataDTO {
private UUID id;
private String alias;
private Integer primaryVersion;
private KeyType keyType;
private List<KeyOperation> allowedOperations;
private Instant createdAt;
private Instant rotatedAt;
}
10 changes: 10 additions & 0 deletions MiniKms/src/main/java/ftn/security/minikms/dto/TokenDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package ftn.security.minikms.dto;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class TokenDTO {
private String token;
}
Loading
Loading