Merge pull request 'PMT-14: JWT Auth' (!1) from story/PMT-14-api-authentizierung-per into trunk
All checks were successful
Quality Check / Validate OAS (push) Successful in 33s
Quality Check / Testing (push) Successful in 58s
Quality Check / Linting (push) Successful in 1m5s
Quality Check / Static Analysis (push) Successful in 1m7s

Reviewed-on: #1
Reviewed-by: SZUT-Rajbir <rajbir2@schule.bremen.de>
Reviewed-by: SZUT-Ole <ole.kueck@hmmh.de>
This commit is contained in:
Dominik Säume 2024-09-27 11:26:16 +00:00
commit 083f02a16b
12 changed files with 167 additions and 26 deletions

View file

@ -1,7 +1,7 @@
<component name="ProjectRunConfigurationManager"> <component name="ProjectRunConfigurationManager">
<configuration default="false" name="Run" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot"> <configuration default="false" name="Run" type="SpringBootApplicationConfigurationType" factoryName="Spring Boot">
<module name="Project_Management_Tool.main" /> <module name="Project_Management_Tool.main" />
<option name="SPRING_BOOT_MAIN_CLASS" value="de.hmmh.pmt.ProjectManagementToolApplication" /> <option name="SPRING_BOOT_MAIN_CLASS" value="de.hmmh.pmt.OpenAPISpringBoot" />
<method v="2"> <method v="2">
<option name="Make" enabled="true" /> <option name="Make" enabled="true" />
<option name="RunConfigurationTask" enabled="false" run_configuration_name="Postgres" run_configuration_type="docker-deploy" /> <option name="RunConfigurationTask" enabled="false" run_configuration_name="Postgres" run_configuration_type="docker-deploy" />

View file

@ -10,7 +10,7 @@ repositories {
plugins { plugins {
java java
checkstyle checkstyle
id("com.github.spotbugs") version "6.0.22" id("com.github.spotbugs") version "6.0.23"
id("org.springframework.boot") version "3.3.3" id("org.springframework.boot") version "3.3.3"
id("io.spring.dependency-management") version "1.1.6" id("io.spring.dependency-management") version "1.1.6"
id("org.hidetake.swagger.generator") version "2.19.2" id("org.hidetake.swagger.generator") version "2.19.2"
@ -44,19 +44,25 @@ configurations {
} }
dependencies { dependencies {
//Spring // Spring
implementation("org.springframework.boot:spring-boot-starter-data-jpa") implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-validation") implementation("org.springframework.boot:spring-boot-starter-validation")
implementation("org.springframework.boot:spring-boot-starter-web") implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.boot:spring-boot-starter-oauth2-client")
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
// Postgres
runtimeOnly("org.postgresql:postgresql") runtimeOnly("org.postgresql:postgresql")
//Lombok // Lombok
compileOnly("org.projectlombok:lombok") compileOnly("org.projectlombok:lombok")
annotationProcessor("org.projectlombok:lombok") annotationProcessor("org.projectlombok:lombok")
//Test // Test
testImplementation("org.springframework.boot:spring-boot-starter-test") testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework.boot:spring-boot-testcontainers") testImplementation("org.springframework.boot:spring-boot-testcontainers")
testImplementation("org.springframework.security:spring-security-test")
testImplementation("org.testcontainers:junit-jupiter") testImplementation("org.testcontainers:junit-jupiter")
testImplementation("org.testcontainers:postgresql") testImplementation("org.testcontainers:postgresql")
testRuntimeOnly("org.junit.platform:junit-platform-launcher") testRuntimeOnly("org.junit.platform:junit-platform-launcher")
@ -64,6 +70,7 @@ dependencies {
//OAS //OAS
swaggerCodegen("io.swagger.codegen.v3:swagger-codegen-cli:3.0.61") swaggerCodegen("io.swagger.codegen.v3:swagger-codegen-cli:3.0.61")
implementation("io.swagger.core.v3:swagger-annotations:2.2.22") implementation("io.swagger.core.v3:swagger-annotations:2.2.22")
implementation("jakarta.xml.bind:jakarta.xml.bind-api") //Needed for XML/HTML Validation
} }
swaggerSources { swaggerSources {
@ -73,7 +80,6 @@ swaggerSources {
val validationTask = validation val validationTask = validation
code(delegateClosureOf<GenerateSwaggerCode> { code(delegateClosureOf<GenerateSwaggerCode> {
language = "spring" language = "spring"
components = listOf("models", "apis")
code.rawOptions = code.rawOptions =
listOf("--ignore-file-override=" + file("${rootDir}/src/main/resources/.codegen-ignore").absolutePath) listOf("--ignore-file-override=" + file("${rootDir}/src/main/resources/.codegen-ignore").absolutePath)
dependsOn(validationTask) dependsOn(validationTask)
@ -90,6 +96,7 @@ tasks {
} }
} }
withType<SpotBugsTask> { withType<SpotBugsTask> {
excludeFilter.set(file("${rootDir}/src/main/resources/spotbugs-exclude.xml")) excludeFilter.set(file("${rootDir}/src/main/resources/spotbugs-exclude.xml"))
} }
processResources { processResources {

View file

@ -2,7 +2,7 @@ package de.hmmh.pmt;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import de.hmmh.pmt.oas.DefaultApi; import de.hmmh.pmt.oas.DefaultApi;
import de.hmmh.pmt.oas.models.HelloOut; import de.hmmh.pmt.dtos.HelloOut;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;

View file

@ -1,13 +0,0 @@
package de.hmmh.pmt;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProjectManagementToolApplication {
public static void main(String[] args) {
SpringApplication.run(ProjectManagementToolApplication.class, args);
}
}

View file

@ -0,0 +1,57 @@
package de.hmmh.pmt.auth;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.session.HttpSessionEventPublisher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class AuthConfig {
private final JWT jwt;
AuthConfig(JWT jwt) {
this.jwt = jwt;
}
@Bean
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
@Bean
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(sessionRegistry());
}
@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.anyRequest()
.authenticated()
)
.oauth2ResourceServer(resourceServer -> resourceServer
.jwt(jwt -> jwt
.jwtAuthenticationConverter(this.jwt.jwtAuthenticationConverter())
)
);
return http.build();
}
}

View file

@ -0,0 +1,69 @@
package de.hmmh.pmt.auth;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Component
public class JWT implements LogoutHandler {
private static final String REALM_ACCESS_CLAIM = "realm_access";
private static final String ROLES_CLAIM = "roles";
private static final String ROLE_PREFIX = "ROLE_";
private static final String OIDC_LOGOUT_ROUTE = "/protocol/openid-connect/logout";
private static final String OIDC_TOKEN_HINT_QUERY_PARAMETER = "id_token_hin";
private final RestTemplate template = new RestTemplate();
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
OidcUser user = (OidcUser) authentication.getPrincipal();
String endSessionEndpoint = user.getIssuer() + OIDC_LOGOUT_ROUTE;
UriComponentsBuilder builder = UriComponentsBuilder
.fromUriString(endSessionEndpoint)
.queryParam(OIDC_TOKEN_HINT_QUERY_PARAMETER, user.getIdToken().getTokenValue());
ResponseEntity<String> logoutResponse = template.getForEntity(builder.toUriString(), String.class);
if (logoutResponse.getStatusCode().is2xxSuccessful()) {
System.out.println("Logged out successfully");
} else {
System.out.println("Failed to logout");
}
}
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwt -> {
List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
Map<String, Object> realmAccess = jwt.getClaim(REALM_ACCESS_CLAIM);
if (realmAccess == null || !realmAccess.containsKey(ROLES_CLAIM)) {
return grantedAuthorities;
}
Object rolesClaim = realmAccess.get(ROLES_CLAIM);
if (!(rolesClaim instanceof List<?>)) {
return grantedAuthorities;
}
for (Object role : (List<?>) rolesClaim) {
assert role instanceof String;
grantedAuthorities.add(new SimpleGrantedAuthority(ROLE_PREFIX + role));
}
return grantedAuthorities;
});
return jwtAuthenticationConverter;
}
}

View file

@ -1,2 +1,4 @@
**/*ApiController.java **/*ApiController.java
**/org/openapitools/configuration/ **/*application.properties
**/io/swagger/configuration/HomeController.java
**/io/swagger/configuration/SwaggerUiConfiguration.java

View file

@ -5,8 +5,15 @@ info:
version: 1.0.0 version: 1.0.0
servers: servers:
- url: /api/v1 - url: /api/v1
security:
- JWTAuth: []
components: components:
securitySchemes:
JWTAuth:
type: http
scheme: bearer
bearerFormat: JWT
schemas: schemas:
HelloOut: HelloOut:
description: "A Test Schema" description: "A Test Schema"

View file

@ -7,3 +7,14 @@ spring.datasource.url=jdbc:postgresql://localhost:5432/pmt
spring.datasource.username=pmt_user spring.datasource.username=pmt_user
spring.datasource.password=pmt123 spring.datasource.password=pmt123
spring.jpa.hibernate.ddl-auto=create-drop spring.jpa.hibernate.ddl-auto=create-drop
# JWT Auth
spring.security.oauth2.client.registration.keycloak.client-id=employee-management-service
spring.security.oauth2.client.registration.keycloak.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.keycloak.scope=openid
spring.security.oauth2.client.provider.keycloak.issuer-uri=https://keycloak.szut.dev/auth/realms/szut
spring.security.oauth2.client.provider.keycloak.user-name-attribute=preferred_username
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://keycloak.szut.dev/auth/realms/szut
# Debugging
logging.level.org.springframework.security=DEBUG

View file

@ -6,4 +6,5 @@
<suppressions> <suppressions>
<suppress files="[\\/]de[\\/]hmmh[\\/]pmt[\\/]oas" checks="."/> <suppress files="[\\/]de[\\/]hmmh[\\/]pmt[\\/]oas" checks="."/>
<suppress files="[\\/]de[\\/]hmmh[\\/]pmt[\\/]dtos" checks="."/>
</suppressions> </suppressions>

View file

@ -1,7 +1,7 @@
{ {
"modelPackage": "de.hmmh.pmt.oas.models", "modelPackage": "de.hmmh.pmt.dtos",
"apiPackage": "de.hmmh.pmt.oas", "apiPackage": "de.hmmh.pmt.oas",
"invokerPackage": "de.hmmh.pmt.oas", "invokerPackage": "de.hmmh.pmt",
"java8": false, "java8": false,
"java11": true, "java11": true,
"dateLibrary": "java11", "dateLibrary": "java11",

View file

@ -1,5 +1,5 @@
<FindBugsFilter> <FindBugsFilter xmlns="https://raw.githubusercontent.com/spotbugs/spotbugs/4.8.6/spotbugs/etc/findbugsfilter.xsd">
<Match> <Match>
<Package name="de.hmmh.pmt.oas"/> <Class name="de.hmmh.pmt.OpenAPISpringBoot$ExitException"/>
</Match> </Match>
</FindBugsFilter> </FindBugsFilter>