diff --git a/GetBearerToken.http b/GetBearerToken.http index d198851..f5209ca 100644 --- a/GetBearerToken.http +++ b/GetBearerToken.http @@ -1,4 +1,6 @@ POST https://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token Content-Type: application/x-www-form-urlencoded -grant_type=password&client_id=employee-management-service&username=user&password=test \ No newline at end of file +grant_type=password&client_id=employee-management-service&username=user&password=test + +> {% client.global.set("auth_token", response.body.access_token); %} \ No newline at end of file diff --git a/Readme.md b/Readme.md index 3f1c15e..f83514d 100644 --- a/Readme.md +++ b/Readme.md @@ -1,65 +1,65 @@ -# Starter für das LF08 Projekt - -## Requirements -* Docker https://docs.docker.com/get-docker/ -* Docker compose (bei Windows und Mac schon in Docker enthalten) https://docs.docker.com/compose/install/ - -## Endpunkt -``` -http://localhost:8080 -``` -## Swagger -``` -http://localhost:8080/swagger -``` - - -# Postgres -### Terminal öffnen -für alles gilt, im Terminal im Ordner docker/local sein -```bash -cd docker/local -``` -### Postgres starten -```bash -docker compose up -``` -Achtung: Der Docker-Container läuft dauerhaft! Wenn er nicht mehr benötigt wird, sollten Sie ihn stoppen. - -### Postgres stoppen -```bash -docker compose down -``` - -### Postgres Datenbank wipen, z.B. bei Problemen -```bash -docker compose down -docker volume rm local_lf8_starter_postgres_data -docker compose up -``` - -### Intellij-Ansicht für Postgres Datenbank einrichten -```bash -1. Lasse den Docker-Container mit der PostgreSQL-Datenbank laufen -2. im Ordner resources die Datei application.properties öffnen und die URL der Datenbank kopieren -3. rechts im Fenster den Reiter Database öffnen -4. In der Database-Symbolleiste auf das Datenbanksymbol mit dem Schlüssel klicken -5. auf das Pluszeichen klicken -6. Datasource from URL auswählen -7. URL der DB einfügen und PostgreSQL-Treiber auswählen, mit OK bestätigen -8. Username lf8_starter und Passwort secret eintragen (siehe application.properties), mit Apply bestätigen -9. im Reiter Schemas alle Häkchen entfernen und lediglich vor lf8_starter_db und public Häkchen setzen -10. mit Apply und ok bestätigen -``` -# Keycloak - -### Keycloak Token -1. Auf der Projektebene [GetBearerToken.http](GetBearerToken.http) öffnen. -2. Neben der Request auf den grünen Pfeil drücken -3. Aus dem Reponse das access_token kopieren - -# Conventions - -### Commits -Commits and merge request names MUST be done as documented here: https://www.conventionalcommits.org/en/v1.0.0/ +# Starter für das LF08 Projekt + +## Requirements +* Docker https://docs.docker.com/get-docker/ +* Docker compose (bei Windows und Mac schon in Docker enthalten) https://docs.docker.com/compose/install/ + +## Endpunkt +``` +http://localhost:8080 +``` +## Swagger +``` +http://localhost:8080/swagger +``` + + +# Postgres +### Terminal öffnen +für alles gilt, im Terminal im Ordner docker/local sein +```bash +cd docker/local +``` +### Postgres starten +```bash +docker compose up +``` +Achtung: Der Docker-Container läuft dauerhaft! Wenn er nicht mehr benötigt wird, sollten Sie ihn stoppen. + +### Postgres stoppen +```bash +docker compose down +``` + +### Postgres Datenbank wipen, z.B. bei Problemen +```bash +docker compose down +docker volume rm local_lf8_starter_postgres_data +docker compose up +``` + +### Intellij-Ansicht für Postgres Datenbank einrichten +```bash +1. Lasse den Docker-Container mit der PostgreSQL-Datenbank laufen +2. im Ordner resources die Datei application.properties öffnen und die URL der Datenbank kopieren +3. rechts im Fenster den Reiter Database öffnen +4. In der Database-Symbolleiste auf das Datenbanksymbol mit dem Schlüssel klicken +5. auf das Pluszeichen klicken +6. Datasource from URL auswählen +7. URL der DB einfügen und PostgreSQL-Treiber auswählen, mit OK bestätigen +8. Username lf8_starter und Passwort secret eintragen (siehe application.properties), mit Apply bestätigen +9. im Reiter Schemas alle Häkchen entfernen und lediglich vor lf8_starter_db und public Häkchen setzen +10. mit Apply und ok bestätigen +``` +# Keycloak + +### Keycloak Token +1. Auf der Projektebene [GetBearerToken.http](GetBearerToken.http) öffnen. +2. Neben der Request auf den grünen Pfeil drücken +3. Aus dem Reponse das access_token kopieren + +# Conventions + +### Commits +Commits and merge request names MUST be done as documented here: https://www.conventionalcommits.org/en/v1.0.0/ Merge request titles MAY also include the ticket id from our jira tickets if the Merge request is part of a ticket. The jira board can be opened through the issues tab. \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts index 8aa3eba..43341a6 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,61 +1,62 @@ -plugins { - java - id("org.springframework.boot") version "3.3.4" - id("io.spring.dependency-management") version "1.1.6" - id("checkstyle") -} - -tasks.withType { - reports { - // Disable HTML report - html.required.set(false) - - // Disable XML report - xml.required.set(false) - } -} - -group = "de.szut" -version = "0.0.1-SNAPSHOT" - -tasks.test { - useJUnitPlatform() - - // Activate the 'test' profile for Spring during tests - systemProperty("spring.profiles.active", "test") -} - -java { - toolchain { - languageVersion = JavaLanguageVersion.of(21) - } -} - -configurations { - compileOnly { - extendsFrom(configurations.annotationProcessor.get()) - } -} - -repositories { - mavenCentral() -} - -dependencies { - implementation("org.springframework.boot:spring-boot-starter-data-jpa") - implementation("org.springframework.boot:spring-boot-starter-web") - compileOnly("org.projectlombok:lombok") - annotationProcessor("org.projectlombok:lombok") - testImplementation("org.springframework.boot:spring-boot-starter-test") - testRuntimeOnly("org.junit.platform:junit-platform-launcher") - implementation("org.springframework.boot:spring-boot-starter-security") - implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server:3.3.4") - implementation("org.springframework.boot:spring-boot-starter-oauth2-client:3.3.4") - runtimeOnly("org.postgresql:postgresql") - implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0") - testImplementation("com.h2database:h2") -} - -tasks.withType { - useJUnitPlatform() -} +plugins { + java + id("org.springframework.boot") version "3.3.4" + id("io.spring.dependency-management") version "1.1.6" + id("checkstyle") +} + +tasks.withType { + reports { + // Disable HTML report + html.required.set(false) + + // Disable XML report + xml.required.set(false) + } +} + +group = "de.szut" +version = "0.0.1-SNAPSHOT" + +tasks.test { + useJUnitPlatform() + + // Activate the 'test' profile for Spring during tests + systemProperty("spring.profiles.active", "test") +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +configurations { + compileOnly { + extendsFrom(configurations.annotationProcessor.get()) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.springframework.boot:spring-boot-starter-data-jpa") + implementation("org.springframework.boot:spring-boot-starter-web") + implementation("org.springframework.boot:spring-boot-starter-validation") + compileOnly("org.projectlombok:lombok") + annotationProcessor("org.projectlombok:lombok") + testImplementation("org.springframework.boot:spring-boot-starter-test") + testRuntimeOnly("org.junit.platform:junit-platform-launcher") + implementation("org.springframework.boot:spring-boot-starter-security") + implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server:3.3.4") + implementation("org.springframework.boot:spring-boot-starter-oauth2-client:3.3.4") + runtimeOnly("org.postgresql:postgresql") + implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.6.0") + testImplementation("com.h2database:h2") +} + +tasks.withType { + useJUnitPlatform() +} diff --git a/config/checkstyle/checkstyle-ignore.xml b/config/checkstyle/checkstyle-ignore.xml index fe3b2fe..5ec61a5 100644 --- a/config/checkstyle/checkstyle-ignore.xml +++ b/config/checkstyle/checkstyle-ignore.xml @@ -1,9 +1,9 @@ - - - - - - + + + + + + diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index d8f0701..3c18de8 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -1,23 +1,23 @@ - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index df97d72..b9ddd88 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,7 +1,7 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index f5feea6..ec19934 100755 --- a/gradlew +++ b/gradlew @@ -1,252 +1,252 @@ -#!/bin/sh - -# -# Copyright © 2015-2021 the original authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# SPDX-License-Identifier: Apache-2.0 -# - -############################################################################## -# -# Gradle start up script for POSIX generated by Gradle. -# -# Important for running: -# -# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is -# noncompliant, but you have some other compliant shell such as ksh or -# bash, then to run this script, type that shell name before the whole -# command line, like: -# -# ksh Gradle -# -# Busybox and similar reduced shells will NOT work, because this script -# requires all of these POSIX shell features: -# * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». -# -# Important for patching: -# -# (2) This script targets any POSIX shell, so it avoids extensions provided -# by Bash, Ksh, etc; in particular arrays are avoided. -# -# The "traditional" practice of packing multiple parameters into a -# space-separated string is a well documented source of bugs and security -# problems, so this is (mostly) avoided, by progressively accumulating -# options in "$@", and eventually passing that to Java. -# -# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, -# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; -# see the in-line comments for details. -# -# There are tweaks for specific operating systems such as AIX, CygWin, -# Darwin, MinGW, and NonStop. -# -# (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt -# within the Gradle project. -# -# You can find Gradle at https://github.com/gradle/gradle/. -# -############################################################################## - -# Attempt to set APP_HOME - -# Resolve links: $0 may be a link -app_path=$0 - -# Need this for daisy-chained symlinks. -while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path - [ -h "$app_path" ] -do - ls=$( ls -ld "$app_path" ) - link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -# This is normally unused -# shellcheck disable=SC2034 -APP_BASE_NAME=${0##*/} -# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s -' "$PWD" ) || exit - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - if ! command -v java >/dev/null 2>&1 - then - die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' - -# Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, -# and any embedded shellness will be escaped. -# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be -# treated as '${Hostname}' itself on the command line. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ - "$@" - -# Stop when "xargs" is not available. -if ! command -v xargs >/dev/null 2>&1 -then - die "xargs is not available" -fi - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/requests/createProject.http b/requests/createProject.http new file mode 100644 index 0000000..add2394 --- /dev/null +++ b/requests/createProject.http @@ -0,0 +1,15 @@ +### GET request to example server +POST http://localhost:8080/projects +Authorization: Bearer {{auth_token}} +Content-Type: application/json + +{ + "name": "name", + "leading_employee": 1, + "employees": [2, 3], + "contractor": 4, + "contractorName": "Peter File", + "comment": "goal of project", + "startDate": "01.01.2000", + "plannedEndDate": "01.01.2001" +} \ No newline at end of file diff --git a/src/main/java/de/szut/lf8_starter/config/OpenAPIConfiguration.java b/src/main/java/de/szut/lf8_starter/config/OpenAPIConfiguration.java index 1b2282b..76a6f58 100644 --- a/src/main/java/de/szut/lf8_starter/config/OpenAPIConfiguration.java +++ b/src/main/java/de/szut/lf8_starter/config/OpenAPIConfiguration.java @@ -1,60 +1,60 @@ -package de.szut.lf8_starter.config; - - - -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.SecurityRequirement; -import io.swagger.v3.oas.models.security.SecurityScheme; -import io.swagger.v3.oas.models.servers.Server; -import jakarta.servlet.ServletContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - - -@Configuration -public class OpenAPIConfiguration { - - private ServletContext context; - - public OpenAPIConfiguration(ServletContext context) { - this.context = context; - } - - - @Bean - public OpenAPI springShopOpenAPI( - // @Value("${info.app.version}") String appVersion, - ) { - final String securitySchemeName = "bearerAuth"; - - return new OpenAPI() - .addServersItem(new Server().url(this.context.getContextPath())) - .info(new Info() - .title("LF8 project starter") - .description("\n## Auth\n" + - "\n## Authentication\n" + "\nThis Hello service uses JWTs to authenticate requests. You will receive a bearer token by making a POST-Request in IntelliJ on:\n\n" + - "\n" + - "```\nPOST http://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token\nContent-Type: application/x-www-form-urlencoded\ngrant_type=password&client_id=employee-management-service&username=user&password=test\n```\n" + - "\n" + - "\nor by CURL\n" + - "```\ncurl -X POST 'http://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token'\n--header 'Content-Type: application/x-www-form-urlencoded'\n--data-urlencode 'grant_type=password'\n--data-urlencode 'client_id=employee-management-service'\n--data-urlencode 'username=user'\n--data-urlencode 'password=test'\n```\n" + - "\nTo get a bearer-token in Postman, you have to follow the instructions in \n [Postman-Documentation](https://documenter.getpostman.com/view/7294517/SzmfZHnd).") - - .version("0.1")) - .addSecurityItem(new SecurityRequirement().addList(securitySchemeName)) - .components( - new Components() - .addSecuritySchemes(securitySchemeName, - new SecurityScheme() - .name(securitySchemeName) - .type(SecurityScheme.Type.HTTP) - .scheme("bearer") - .bearerFormat("JWT") - ) - ); - } - - -} +package de.szut.lf8_starter.config; + + + +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.SecurityRequirement; +import io.swagger.v3.oas.models.security.SecurityScheme; +import io.swagger.v3.oas.models.servers.Server; +import jakarta.servlet.ServletContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + + +@Configuration +public class OpenAPIConfiguration { + + private ServletContext context; + + public OpenAPIConfiguration(ServletContext context) { + this.context = context; + } + + + @Bean + public OpenAPI springShopOpenAPI( + // @Value("${info.app.version}") String appVersion, + ) { + final String securitySchemeName = "bearerAuth"; + + return new OpenAPI() + .addServersItem(new Server().url(this.context.getContextPath())) + .info(new Info() + .title("LF8 project starter") + .description("\n## Auth\n" + + "\n## Authentication\n" + "\nThis Hello service uses JWTs to authenticate requests. You will receive a bearer token by making a POST-Request in IntelliJ on:\n\n" + + "\n" + + "```\nPOST http://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token\nContent-Type: application/x-www-form-urlencoded\ngrant_type=password&client_id=employee-management-service&username=user&password=test\n```\n" + + "\n" + + "\nor by CURL\n" + + "```\ncurl -X POST 'http://keycloak.szut.dev/auth/realms/szut/protocol/openid-connect/token'\n--header 'Content-Type: application/x-www-form-urlencoded'\n--data-urlencode 'grant_type=password'\n--data-urlencode 'client_id=employee-management-service'\n--data-urlencode 'username=user'\n--data-urlencode 'password=test'\n```\n" + + "\nTo get a bearer-token in Postman, you have to follow the instructions in \n [Postman-Documentation](https://documenter.getpostman.com/view/7294517/SzmfZHnd).") + + .version("0.1")) + .addSecurityItem(new SecurityRequirement().addList(securitySchemeName)) + .components( + new Components() + .addSecuritySchemes(securitySchemeName, + new SecurityScheme() + .name(securitySchemeName) + .type(SecurityScheme.Type.HTTP) + .scheme("bearer") + .bearerFormat("JWT") + ) + ); + } + + +} diff --git a/src/main/java/de/szut/lf8_starter/exceptionHandling/GlobalExceptionHandler.java b/src/main/java/de/szut/lf8_starter/exceptionHandling/GlobalExceptionHandler.java index 828331b..68a15a7 100644 --- a/src/main/java/de/szut/lf8_starter/exceptionHandling/GlobalExceptionHandler.java +++ b/src/main/java/de/szut/lf8_starter/exceptionHandling/GlobalExceptionHandler.java @@ -3,8 +3,10 @@ package de.szut.lf8_starter.exceptionHandling; import io.swagger.v3.oas.annotations.media.Content; import io.swagger.v3.oas.annotations.responses.ApiResponse; import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.ConstraintViolationException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.context.request.WebRequest; @@ -24,5 +26,26 @@ public class GlobalExceptionHandler { return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND); } + @ExceptionHandler(Exception.class) + public ResponseEntity handleAllOtherExceptions(Exception ex, WebRequest request) { + ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getClass() + " " + ex.getMessage(), request.getDescription(false)); + return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException ex, WebRequest request) { + ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false)); + + return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(ConstraintViolationException.class) + public ResponseEntity handleConstraintViolationException(ConstraintViolationException ex, WebRequest request) { + String errorMessage = ex.getConstraintViolations().stream().findFirst().get().getMessage(); + + ErrorDetails errorDetails = new ErrorDetails(new Date(), errorMessage, request.getDescription(false)); + + return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST); + } } diff --git a/src/main/java/de/szut/lf8_starter/project/GetProjectDto.java b/src/main/java/de/szut/lf8_starter/project/GetProjectDto.java new file mode 100644 index 0000000..86ce087 --- /dev/null +++ b/src/main/java/de/szut/lf8_starter/project/GetProjectDto.java @@ -0,0 +1,43 @@ +package de.szut.lf8_starter.project; + +import com.fasterxml.jackson.annotation.JsonFormat; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDate; +import java.util.List; + +@Getter +@Setter +public class GetProjectDto { + @NotBlank + private String name; + + @NotNull + private long leadingEmployee; + + private List employees; + + @NotNull + private long contractor; + + @NotBlank + private String contractorName; + + @NotBlank + private String comment; + + @NotNull + @JsonFormat(pattern = "dd.MM.yyyy") + private LocalDate startDate; + + @NotNull + @JsonFormat(pattern = "dd.MM.yyyy") + private LocalDate plannedEndDate; + + @NotNull + @JsonFormat(pattern = "dd.MM.yyyy") + private LocalDate endDate; +} diff --git a/src/main/java/de/szut/lf8_starter/project/ProjectEntity.java b/src/main/java/de/szut/lf8_starter/project/ProjectEntity.java index 6596350..d9c35a1 100644 --- a/src/main/java/de/szut/lf8_starter/project/ProjectEntity.java +++ b/src/main/java/de/szut/lf8_starter/project/ProjectEntity.java @@ -37,5 +37,7 @@ public class ProjectEntity { @CreatedDate private LocalDate startDate; + private LocalDate plannedEndDate; + private LocalDate endDate; } diff --git a/src/main/java/de/szut/lf8_starter/project/ProjectMapper.java b/src/main/java/de/szut/lf8_starter/project/ProjectMapper.java new file mode 100644 index 0000000..363ea64 --- /dev/null +++ b/src/main/java/de/szut/lf8_starter/project/ProjectMapper.java @@ -0,0 +1,39 @@ +package de.szut.lf8_starter.project; + +import de.szut.lf8_starter.project.dto.CreateProjectDto; +import org.springframework.stereotype.Service; + +@Service +public class ProjectMapper { + public ProjectEntity mapCreateDtoToEntity(CreateProjectDto createProjectDto) { + ProjectEntity projectEntity = new ProjectEntity(); + + projectEntity.setName(createProjectDto.getName()); + projectEntity.setComment(createProjectDto.getComment()); + projectEntity.setLeadingEmployee(createProjectDto.getLeadingEmployee()); + projectEntity.setEmployees(createProjectDto.getEmployees()); + projectEntity.setContractor(createProjectDto.getContractor()); + projectEntity.setContractorName(createProjectDto.getContractorName()); + projectEntity.setStartDate(createProjectDto.getStartDate()); + projectEntity.setPlannedEndDate(createProjectDto.getPlannedEndDate()); + projectEntity.setEndDate(createProjectDto.getEndDate()); + + return projectEntity; + } + + public GetProjectDto mapToGetDto(ProjectEntity projectEntity) { + GetProjectDto getProjectDto = new GetProjectDto(); + + getProjectDto.setName(projectEntity.getName()); + getProjectDto.setComment(projectEntity.getComment()); + getProjectDto.setLeadingEmployee(projectEntity.getLeadingEmployee()); + getProjectDto.setEmployees(projectEntity.getEmployees()); + getProjectDto.setContractor(projectEntity.getContractor()); + getProjectDto.setContractorName(projectEntity.getContractorName()); + getProjectDto.setStartDate(projectEntity.getStartDate()); + getProjectDto.setPlannedEndDate(projectEntity.getPlannedEndDate()); + getProjectDto.setEndDate(projectEntity.getEndDate()); + + return getProjectDto; + } +} \ No newline at end of file diff --git a/src/main/java/de/szut/lf8_starter/project/ProjectService.java b/src/main/java/de/szut/lf8_starter/project/ProjectService.java new file mode 100644 index 0000000..a12228f --- /dev/null +++ b/src/main/java/de/szut/lf8_starter/project/ProjectService.java @@ -0,0 +1,16 @@ +package de.szut.lf8_starter.project; + +import org.springframework.stereotype.Service; + +@Service +public class ProjectService { + private final ProjectRepository projectRepository; + + public ProjectService(ProjectRepository projectRepository) { + this.projectRepository = projectRepository; + } + + public ProjectEntity create(ProjectEntity projectEntity) { + return this.projectRepository.save(projectEntity); + } +} diff --git a/src/main/java/de/szut/lf8_starter/project/dto/CreateProjectAction.java b/src/main/java/de/szut/lf8_starter/project/dto/CreateProjectAction.java new file mode 100644 index 0000000..f1c6cdc --- /dev/null +++ b/src/main/java/de/szut/lf8_starter/project/dto/CreateProjectAction.java @@ -0,0 +1,42 @@ +package de.szut.lf8_starter.project.dto; + +import de.szut.lf8_starter.project.GetProjectDto; +import de.szut.lf8_starter.project.ProjectEntity; +import de.szut.lf8_starter.project.ProjectMapper; +import de.szut.lf8_starter.project.ProjectService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.responses.ApiResponses; +import jakarta.validation.Valid; +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(value = "/projects") +public class CreateProjectAction { + private final ProjectService projectService; + private final ProjectMapper projectMapper; + + public CreateProjectAction(ProjectService projectService, ProjectMapper mappingService) { + this.projectService = projectService; + this.projectMapper = mappingService; + } + + @Operation(summary = "Creates a new Project") + @ApiResponses(value = { + @ApiResponse(responseCode = "201", description = "created project", content = {@Content(mediaType = "application/json", schema = @Schema(implementation = GetProjectDto.class))}), + @ApiResponse(responseCode = "400", description = "invalid JSON posted", content = @Content), + @ApiResponse(responseCode = "401", description = "not authorized", content = @Content)}) + @PostMapping + public GetProjectDto create(@RequestBody @Valid CreateProjectDto createProjectDto) { + ProjectEntity projectEntity = this.projectMapper.mapCreateDtoToEntity(createProjectDto); + + projectEntity = this.projectService.create(projectEntity); + + return this.projectMapper.mapToGetDto(projectEntity); + } +} diff --git a/src/main/java/de/szut/lf8_starter/project/dto/CreateProjectDto.java b/src/main/java/de/szut/lf8_starter/project/dto/CreateProjectDto.java new file mode 100644 index 0000000..4c6ab0d --- /dev/null +++ b/src/main/java/de/szut/lf8_starter/project/dto/CreateProjectDto.java @@ -0,0 +1,42 @@ +package de.szut.lf8_starter.project.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDate; +import java.util.List; + +@Getter +@Setter +public class CreateProjectDto { + @NotBlank + private String name; + + @NotNull + private long leadingEmployee; + + private List employees; + + @NotNull + private long contractor; + + @NotBlank + private String contractorName; + + @NotBlank + private String comment; + + @JsonFormat(pattern = "dd.MM.yyyy") + @NotNull + private LocalDate startDate; + + @JsonFormat(pattern = "dd.MM.yyyy") + @NotNull + private LocalDate plannedEndDate; + + @JsonFormat(pattern = "dd.MM.yyyy") + private LocalDate endDate; +} diff --git a/src/main/java/de/szut/lf8_starter/security/KeycloakLogoutHandler.java b/src/main/java/de/szut/lf8_starter/security/KeycloakLogoutHandler.java index 8555ef9..e06f2f7 100644 --- a/src/main/java/de/szut/lf8_starter/security/KeycloakLogoutHandler.java +++ b/src/main/java/de/szut/lf8_starter/security/KeycloakLogoutHandler.java @@ -1,49 +1,49 @@ -package de.szut.lf8_starter.security; - -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.ResponseEntity; -import org.springframework.security.core.Authentication; -import org.springframework.security.oauth2.core.oidc.user.OidcUser; -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 jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; - -@Slf4j -@Component -public class KeycloakLogoutHandler implements LogoutHandler { - - - private final RestTemplate restTemplate; - - public KeycloakLogoutHandler(RestTemplate restTemplate) { - this.restTemplate = restTemplate; - } - - @Override - public void logout(HttpServletRequest request, HttpServletResponse response, Authentication auth) { - logout(request, auth); - } - - public void logout(HttpServletRequest request, Authentication auth) { - logoutFromKeycloak((OidcUser) auth.getPrincipal()); - } - - private void logoutFromKeycloak(OidcUser user) { - String endSessionEndpoint = user.getIssuer() + "/protocol/openid-connect/logout"; - UriComponentsBuilder builder = UriComponentsBuilder - .fromUriString(endSessionEndpoint) - .queryParam("id_token_hint", user.getIdToken().getTokenValue()); - - ResponseEntity logoutResponse = restTemplate.getForEntity(builder.toUriString(), String.class); - if (logoutResponse.getStatusCode().is2xxSuccessful()) { - log.info("Successfulley logged out from Keycloak"); - } else { - log.error("Could not propagate logout to Keycloak"); - } - } - -} +package de.szut.lf8_starter.security; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.core.oidc.user.OidcUser; +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 jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@Slf4j +@Component +public class KeycloakLogoutHandler implements LogoutHandler { + + + private final RestTemplate restTemplate; + + public KeycloakLogoutHandler(RestTemplate restTemplate) { + this.restTemplate = restTemplate; + } + + @Override + public void logout(HttpServletRequest request, HttpServletResponse response, Authentication auth) { + logout(request, auth); + } + + public void logout(HttpServletRequest request, Authentication auth) { + logoutFromKeycloak((OidcUser) auth.getPrincipal()); + } + + private void logoutFromKeycloak(OidcUser user) { + String endSessionEndpoint = user.getIssuer() + "/protocol/openid-connect/logout"; + UriComponentsBuilder builder = UriComponentsBuilder + .fromUriString(endSessionEndpoint) + .queryParam("id_token_hint", user.getIdToken().getTokenValue()); + + ResponseEntity logoutResponse = restTemplate.getForEntity(builder.toUriString(), String.class); + if (logoutResponse.getStatusCode().is2xxSuccessful()) { + log.info("Successfulley logged out from Keycloak"); + } else { + log.error("Could not propagate logout to Keycloak"); + } + } + +} diff --git a/src/main/java/de/szut/lf8_starter/security/KeycloakSecurityConfig.java b/src/main/java/de/szut/lf8_starter/security/KeycloakSecurityConfig.java index ea9e354..b12faae 100644 --- a/src/main/java/de/szut/lf8_starter/security/KeycloakSecurityConfig.java +++ b/src/main/java/de/szut/lf8_starter/security/KeycloakSecurityConfig.java @@ -1,97 +1,97 @@ -package de.szut.lf8_starter.security; - -import java.util.*; -import java.util.stream.Collectors; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.http.HttpMethod; -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.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper; -import org.springframework.security.core.session.SessionRegistry; -import org.springframework.security.core.session.SessionRegistryImpl; -import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority; -import org.springframework.security.oauth2.core.user.OAuth2UserAuthority; -import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; -import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; -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 -class KeycloakSecurityConfig { - - private static final String GROUPS = "groups"; - private static final String REALM_ACCESS_CLAIM = "realm_access"; - private static final String ROLES_CLAIM = "roles"; - - private final KeycloakLogoutHandler keycloakLogoutHandler; - - KeycloakSecurityConfig(KeycloakLogoutHandler keycloakLogoutHandler) { - this.keycloakLogoutHandler = keycloakLogoutHandler; - } - - @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 resourceServerFilterChain(HttpSecurity http) throws Exception { - - http.authorizeHttpRequests(auth -> auth - .requestMatchers(new AntPathRequestMatcher("/welcome")) - .permitAll() - .requestMatchers( - new AntPathRequestMatcher("/swagger"), - new AntPathRequestMatcher("/swagger-ui/**"), - new AntPathRequestMatcher("/v3/api-docs/**")) - .permitAll() - .requestMatchers(new AntPathRequestMatcher("/hello/**")) - .hasRole("user") - .requestMatchers(new AntPathRequestMatcher("/roles")) - .authenticated() - .requestMatchers(new AntPathRequestMatcher("/")) - .permitAll() - .anyRequest() - .authenticated()).oauth2ResourceServer(spec -> spec.jwt(Customizer.withDefaults())); - return http.build(); - } - - @Bean - public JwtAuthenticationConverter jwtAuthenticationConverter() { - JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); - jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwt -> { - List grantedAuthorities = new ArrayList<>(); - - Map realmAccess = jwt.getClaim("realm_access"); - if (realmAccess != null && realmAccess.containsKey("roles")) { - List roles = (List) realmAccess.get("roles"); - for (String role : roles) { - grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role)); - } - } - - return grantedAuthorities; - }); - return jwtAuthenticationConverter; - } -} +package de.szut.lf8_starter.security; + +import java.util.*; +import java.util.stream.Collectors; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +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.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper; +import org.springframework.security.core.session.SessionRegistry; +import org.springframework.security.core.session.SessionRegistryImpl; +import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority; +import org.springframework.security.oauth2.core.user.OAuth2UserAuthority; +import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter; +import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter; +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 +class KeycloakSecurityConfig { + + private static final String GROUPS = "groups"; + private static final String REALM_ACCESS_CLAIM = "realm_access"; + private static final String ROLES_CLAIM = "roles"; + + private final KeycloakLogoutHandler keycloakLogoutHandler; + + KeycloakSecurityConfig(KeycloakLogoutHandler keycloakLogoutHandler) { + this.keycloakLogoutHandler = keycloakLogoutHandler; + } + + @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 resourceServerFilterChain(HttpSecurity http) throws Exception { + + http.authorizeHttpRequests(auth -> auth + .requestMatchers(new AntPathRequestMatcher("/welcome")) + .permitAll() + .requestMatchers( + new AntPathRequestMatcher("/swagger"), + new AntPathRequestMatcher("/swagger-ui/**"), + new AntPathRequestMatcher("/v3/api-docs/**")) + .permitAll() + .requestMatchers(new AntPathRequestMatcher("/hello/**")) + .hasRole("user") + .requestMatchers(new AntPathRequestMatcher("/roles")) + .authenticated() + .requestMatchers(new AntPathRequestMatcher("/")) + .permitAll() + .anyRequest() + .authenticated()).oauth2ResourceServer(spec -> spec.jwt(Customizer.withDefaults())); + return http.build(); + } + + @Bean + public JwtAuthenticationConverter jwtAuthenticationConverter() { + JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter(); + jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwt -> { + List grantedAuthorities = new ArrayList<>(); + + Map realmAccess = jwt.getClaim("realm_access"); + if (realmAccess != null && realmAccess.containsKey("roles")) { + List roles = (List) realmAccess.get("roles"); + for (String role : roles) { + grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + role)); + } + } + + return grantedAuthorities; + }); + return jwtAuthenticationConverter; + } +} diff --git a/src/main/resources/application-test.properties b/src/main/resources/application-test.properties index af21e0e..259f612 100644 --- a/src/main/resources/application-test.properties +++ b/src/main/resources/application-test.properties @@ -1,5 +1,5 @@ -spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 -spring.datasource.driver-class-name=org.h2.Driver -spring.datasource.username=sa -spring.datasource.password= +spring.datasource.url=jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1 +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect \ No newline at end of file diff --git a/src/test/java/de/szut/lf8_starter/Lf8StarterApplicationTests.java b/src/test/java/de/szut/lf8_starter/Lf8StarterApplicationTests.java index b5c7f7b..d418f1a 100644 --- a/src/test/java/de/szut/lf8_starter/Lf8StarterApplicationTests.java +++ b/src/test/java/de/szut/lf8_starter/Lf8StarterApplicationTests.java @@ -1,14 +1,14 @@ -package de.szut.lf8_starter; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.TestPropertySource; - -@SpringBootTest -class Lf8StarterApplicationTests { - - @Test - void contextLoads() { - } - -} +package de.szut.lf8_starter; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; + +@SpringBootTest +class Lf8StarterApplicationTests { + + @Test + void contextLoads() { + } + +}