Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add authentication #131

Merged
merged 13 commits into from
Dec 13, 2024
15 changes: 15 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,16 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
Expand Down Expand Up @@ -163,6 +173,11 @@
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<configuration>
<excludes>
<exclude>src/main/java/fr/insee/genesis/configuration/**/*</exclude>
</excludes>
</configuration>
<executions>
<execution>
<id>default-prepare-agent</id>
Expand Down
15 changes: 15 additions & 0 deletions src/main/java/fr/insee/genesis/configuration/Config.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,21 @@ public class Config {
@Value("${fr.insee.genesis.sourcefolder.specifications}")
private String specFolderSource;

@Value("${fr.insee.genesis.oidc.auth-server-url}")
private String authServerUrl;

@Value("${fr.insee.genesis.oidc.realm}")
private String realm;

@Value("${fr.insee.genesis.security.token.oidc-claim-role}")
private String oidcClaimRole;

@Value("${fr.insee.genesis.security.token.oidc-claim-username}")
private String oidcClaimUsername;

@Value("#{'${fr.insee.genesis.security.whitelist-matchers}'.split(',')}")
private String[] whiteList;

private final String logFolder;

//Extract log folder from log filename property
Expand Down
Original file line number Diff line number Diff line change
@@ -1,28 +1,73 @@
package fr.insee.genesis.configuration;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.*;
loichenninger marked this conversation as resolved.
Show resolved Hide resolved
import io.swagger.v3.oas.models.servers.Server;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringDocConfiguration {

@Value("${fr.insee.genesis.version}")
private String projectVersion;
@Value("${fr.insee.genesis.version}")
private String projectVersion;
public static final String BEARERSCHEME = "bearerAuth";
public static final String OAUTH2SCHEME = "oauth2";

@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.addServersItem(new Server().url("/"))
.info(new Info()
.title("Genesis API")
.description("Rest Endpoints and services to communicate with Genesis database")
.version(projectVersion)
);
}
@Bean
@ConditionalOnProperty(name = "fr.insee.genesis.authentication", havingValue = "NONE")
public OpenAPI noAuthOpenAPI() {
return generateOpenAPI();
}

@Bean
@ConditionalOnProperty(name = "fr.insee.genesis.authentication", havingValue = "OIDC")
public OpenAPI oidcOpenAPI(Config config) {
String authUrl = config.getAuthServerUrl() + "/realms/" + config.getRealm() + "/protocol/openid-connect";
return generateOpenAPI()
.addSecurityItem(new SecurityRequirement().addList(OAUTH2SCHEME))
.addSecurityItem(new SecurityRequirement().addList(BEARERSCHEME))
.components(
new Components()
.addSecuritySchemes(OAUTH2SCHEME,
new SecurityScheme()
.name(OAUTH2SCHEME)
.type(SecurityScheme.Type.OAUTH2)
.flows(getFlows(authUrl))
)
.addSecuritySchemes(BEARERSCHEME,
new SecurityScheme()
.name(BEARERSCHEME)
.type(SecurityScheme.Type.HTTP)
.scheme("bearer")
.bearerFormat("JWT")
)
);
}

private OpenAPI generateOpenAPI() {
return new OpenAPI()
.addServersItem(new Server().url("/"))
.info(new Info()
.title("Genesis API")
.description("Rest Endpoints and services to communicate with Genesis database")
.version(projectVersion)
);
}

private OAuthFlows getFlows(String authUrl) {
OAuthFlows flows = new OAuthFlows();
OAuthFlow flow = new OAuthFlow();
Scopes scopes = new Scopes();
flow.setAuthorizationUrl(authUrl + "/auth");
flow.setTokenUrl(authUrl + "/token");
flow.setRefreshUrl(authUrl + "/token");
flow.setScopes(scopes);
return flows.authorizationCode(flow);
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package fr.insee.genesis.configuration.auth.security;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Expand All @@ -10,7 +10,7 @@

@Configuration
@EnableWebSecurity
@ConditionalOnMissingBean(OIDCSecurityConfig.class)
@ConditionalOnProperty(name = "fr.insee.genesis.authentication", havingValue = "NONE")
public class DefaultSecurityConfig {

@Bean
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,48 @@
package fr.insee.genesis.configuration.auth.security;

import fr.insee.genesis.configuration.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
@Slf4j
@ConditionalOnProperty(name = "fr.insee.genesis.authentication", havingValue = "OIDC")
public class OIDCSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable).authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
return http.build();
Config config;
@Autowired
public OIDCSecurityConfig(Config config) {
this.config = config;
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
for (var pattern : config.getWhiteList()) {
http.authorizeHttpRequests(authorize ->
authorize
.requestMatchers(AntPathRequestMatcher.antMatcher(pattern)).permitAll()
);
}
http
.authorizeHttpRequests(configurer -> configurer
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
return http.build();
}

}
9 changes: 8 additions & 1 deletion src/main/resources/application-dev.properties
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,11 @@ fr.insee.genesis.persistence.database.mongodb.port=27017
fr.insee.genesis.persistence.database.mongodb.database=CollectedDataRepository
fr.insee.genesis.persistence.database.mongodb.username=user

#fr.insee.genesis.persistence.database.mongodb.password in Vault
#fr.insee.genesis.persistence.database.mongodb.password in Vault

#--------------------------------------------------------------------------
# Keycloak configuration
#--------------------------------------------------------------------------
fr.insee.genesis.oidc.auth-server-url=***
fr.insee.genesis.oidc.realm=***
springdoc.swagger-ui.oauth.client-id=***
9 changes: 8 additions & 1 deletion src/main/resources/application-preprod.properties
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,11 @@ fr.insee.genesis.persistence.database.mongodb.port=27017
fr.insee.genesis.persistence.database.mongodb.database=CollectedDataRepository
fr.insee.genesis.persistence.database.mongodb.username=user

#fr.insee.genesis.persistence.database.mongodb.password in Vault
#fr.insee.genesis.persistence.database.mongodb.password in Vault

#--------------------------------------------------------------------------
# Keycloak configuration
#--------------------------------------------------------------------------
fr.insee.genesis.oidc.auth-server-url=***
fr.insee.genesis.oidc.realm=***
springdoc.swagger-ui.oauth.client-id=***
9 changes: 8 additions & 1 deletion src/main/resources/application-prod.properties
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,11 @@ fr.insee.genesis.persistence.database.mongodb.port=27017
fr.insee.genesis.persistence.database.mongodb.database=CollectedDataRepository
fr.insee.genesis.persistence.database.mongodb.username=user

#fr.insee.genesis.persistence.database.mongodb.password in Vault
#fr.insee.genesis.persistence.database.mongodb.password in Vault

#--------------------------------------------------------------------------
# Keycloak configuration
#--------------------------------------------------------------------------
fr.insee.genesis.oidc.auth-server-url=***
fr.insee.genesis.oidc.realm=***
springdoc.swagger-ui.oauth.client-id=***
11 changes: 10 additions & 1 deletion src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,23 @@ spring.profiles.active=local
#--------------------------------------------------------------------------
# Global configuration
#--------------------------------------------------------------------------
fr.insee.genesis.authentication = NONE
fr.insee.genesis.authentication = OIDC

#--------------------------------------------------------------------------
# Configuration for springdoc / swagger
#--------------------------------------------------------------------------
[email protected]@
#To make swagger-ui display the actuator endpoints
springdoc.show-actuator=true
springdoc.swagger-ui.oauth2RedirectUrl=${fr.insee.genesis.application.host.url}/swagger-ui/oauth2-redirect.html

#--------------------------------------------------------------------------
# Security
#--------------------------------------------------------------------------
fr.insee.genesis.security.token.oidc-claim-role=realm_access.roles
fr.insee.genesis.security.token.oidc-claim-username=name
spring.security.oauth2.resourceserver.jwt.issuer-uri=${fr.insee.genesis.oidc.auth-server-url}/realms/${fr.insee.genesis.oidc.realm}
fr.insee.genesis.security.whitelist-matchers=/v3/api-docs/**,/swagger-ui/**,/swagger-ui.html,/actuator/**,/error,/,/health-check/**

#--------------------------------------------------------------------------
# Actuator
Expand Down
Loading