Add AuthorizeReturnObject Sample

Closes gh-4
This commit is contained in:
Josh Cummings
2024-10-09 15:32:13 -06:00
parent e24b5b84db
commit 11f42986b0
31 changed files with 1084 additions and 73 deletions

View File

@@ -0,0 +1,72 @@
= A CRUD Spring LDAP application using Spring Boot
The application is protected by Spring Security and uses an embedded UnboundID container for its LDAP server.
You can authenticate with HTTP basic using `dante`/`secret`:
[source,bash]
----
curl --user dante:secret localhost:8080/people
----
And you should see a response like this one:
[source,bash]
----
[
[
{
"dn": "uid=dante,ou=people",
"lastName": "Alvarez",
"username": "dante"
},
{
"dn": "uid=hal,ou=people",
"lastName": "Hal",
"username": "hal"
},
{
"dn": "uid=may,ou=people",
"lastName": "May",
"username": "may"
},
// ...
}
----
Or, if you use `hal`/`sorrydave`, you'll see more information:
[source,bash]
----
[
{
"dn": "uid=dante,ou=people",
"lastName": "Alvarez",
"name": "Dante Alvarez",
"username": "dante"
},
{
"dn": "uid=hal,ou=people",
"lastName": "Hal",
"name": "Hal 2000",
"username": "hal"
},
{
"dn": "uid=may,ou=people",
"lastName": "May",
"name": "May Bea",
"username": "may"
},
// ...
----
The sample supports the following operations:
* `GET /people` - retrieve all the people in the application
* `GET /people/uid=may,ou=people` - retrieve May Bea's details; you can replace the DN with another one to see another person's information
* `GET /people/me` - retrieve the current user's details
* `POST /people` - add a new person, for example `{ "username": "newuser", "sn": "User", "cn": "New User" }`
* `PUT /people/uid=may,ou=people` - update May Bea's details, supports partial update; you can replace the DN with another one to make changes to a different entry
* `DELETE /people/uid=may,ou=people` - remove May Bea from the system; you can replace the DN with another one to remove a different entry
To run the sample, do `./gradlew :bootRun`.

View File

@@ -0,0 +1,30 @@
plugins {
alias(libs.plugins.org.springframework.boot)
alias(libs.plugins.io.spring.dependency.management)
id "nebula.integtest" version "8.2.0"
id 'java'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/milestone" }
maven { url "https://repo.spring.io/snapshot" }
}
ext['spring-security.version'] = "6.4.0-SNAPSHOT"
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-ldap'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.security:spring-security-ldap'
implementation 'com.unboundid:unboundid-ldapsdk:7.0.1'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.security:spring-security-test'
}
tasks.withType(Test).configureEach {
useJUnitPlatform()
}

View File

@@ -0,0 +1,4 @@
version=6.1.1
spring-ldap.version=3.3.0-SNAPSHOT
org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError
org.gradle.caching=true

View File

@@ -0,0 +1,12 @@
[versions]
org-springframework-boot = "3.4.0-SNAPSHOT"
[libraries]
org-springframework-spring-framework-bom = "org.springframework:spring-framework-bom:6.2.0-M6"
org-springframework-data-spring-data-bom = "org.springframework.data:spring-data-bom:2024.0.2"
org-springframework-ldap-spring-ldap-core = "org.springframework.ldap:spring-ldap-core:3.3.0-SNAPSHOT"
org-springframework-ldap-spring-ldap-test = "org.springframework.ldap:spring-ldap-test:3.3.0-SNAPSHOT"
[plugins]
io-spring-dependency-management = { id = "io.spring.dependency-management", version = "1.1.6" }
org-springframework-boot = { id = "org.springframework.boot", version.ref = "org-springframework-boot" }

Binary file not shown.

View File

@@ -0,0 +1,6 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

244
servlet/spring-boot/java/security/gradlew vendored Executable file
View File

@@ -0,0 +1,244 @@
#!/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.
#
##############################################################################
#
# 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/subprojects/plugins/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##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# 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"'
# 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
which java >/dev/null 2>&1 || 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
# 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=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=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
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
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" "$@"

View File

@@ -0,0 +1,92 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,8 @@
pluginManagement {
repositories {
mavenCentral()
gradlePluginPortal()
maven { url 'https://repo.spring.io/milestone' }
maven { url "https://repo.spring.io/snapshot" }
}
}

View File

@@ -0,0 +1,95 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example;
import javax.naming.Name;
import example.security.NullMethodAuthorizationDeniedHandler;
import org.springframework.ldap.odm.annotations.Attribute;
import org.springframework.ldap.odm.annotations.DnAttribute;
import org.springframework.ldap.odm.annotations.Entry;
import org.springframework.ldap.odm.annotations.Id;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authorization.method.HandleAuthorizationDenied;
@Entry(objectClasses = { "inetOrgPerson", "organizationalPerson", "person", "top" }, base = "ou=people")
public class Person {
@Id
private Name dn;
@DnAttribute(value = "uid", index = 1)
@Attribute(name = "uid")
private String username;
@Attribute(name = "cn")
private String name;
@Attribute(name = "sn")
private String lastName;
public Person() {
}
public Person(String username) {
this.username = username;
}
public Person(Person person) {
this.dn = person.getDn();
this.username = person.getUsername();
this.name = person.getName();
this.lastName = person.getLastName();
}
public Name getDn() {
return this.dn;
}
public void setDn(Name dn) {
this.dn = dn;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
@HandleAuthorizationDenied(handlerClass = NullMethodAuthorizationDeniedHandler.class)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}

View File

@@ -0,0 +1,84 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example;
import java.util.Collection;
import java.util.List;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import example.ldap.DirContextOperationsMapper;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapClient;
import org.springframework.ldap.odm.core.ObjectDirectoryMapper;
import org.springframework.ldap.odm.core.impl.DefaultObjectDirectoryMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper;
public final class PersonContextMapper implements UserDetailsContextMapper {
private final LdapClient ldap;
private final ObjectDirectoryMapper odm = new DefaultObjectDirectoryMapper();
public PersonContextMapper(LdapClient ldap) {
this.ldap = ldap;
}
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
Collection<? extends GrantedAuthority> authorities) {
Person person = this.odm.mapFromLdapDataEntry(ctx, Person.class);
DirContextOperationsMapper<String> toAuthority = (c) -> {
List<String> members = List.of(c.getStringAttributes("uniqueMember"));
return (members.contains(ctx.getNameInNamespace())) ? "ROLE_ADMIN" : "ROLE_USER";
};
String authority = this.ldap.search().name("cn=managers,ou=groups").toObject(toAuthority);
return new UserDetailsPerson(person, authority);
}
@Override
public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
throw new UnsupportedOperationException("not supported");
}
@JsonSerialize(as = Person.class)
public static class UserDetailsPerson extends Person implements UserDetails {
Collection<GrantedAuthority> authorities;
public UserDetailsPerson(Person person, String authority) {
super(person);
this.authorities = List.of(new SimpleGrantedAuthority(authority));
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.authorities;
}
@Override
public String getPassword() {
return null;
}
}
}

View File

@@ -0,0 +1,113 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example;
import java.io.IOException;
import javax.naming.Name;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.ModificationItem;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapClient;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authorization.method.AuthorizeReturnObject;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Controller for "/".
*
* @author Josh Cummings
*/
@RestController
@RequestMapping("/people")
@AuthorizeReturnObject
public class PersonController {
private final PersonRepository persons;
private final ObjectMapper mapper;
private final LdapClient ldap;
public PersonController(PersonRepository persons, ObjectMapper mapper, LdapClient ldap) {
this.persons = persons;
this.mapper = mapper;
this.ldap = ldap;
}
@GetMapping
@PreAuthorize("hasAuthority('ROLE_USER')")
public Iterable<Person> list() {
Iterable<Person> people = this.persons.findAll();
return people;
}
@GetMapping("/me")
@PreAuthorize("isAuthenticated()")
public Person me(@AuthenticationPrincipal Person person) {
return person;
}
@GetMapping("/{uid}")
@PreAuthorize("hasAuthority('ROLE_USER')")
public Person get(@PathVariable("uid") Name uid) {
return this.persons.findByDn(uid);
}
@PostMapping
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public Person create(@RequestBody Person person) {
return this.persons.save(person);
}
@PutMapping("/{uid}")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public Person update(@PathVariable("uid") Name uid, @RequestBody String person) throws IOException {
Person toUpdate = this.persons.findByDn(uid);
this.mapper.readerForUpdating(toUpdate).readValue(person, Person.class);
toUpdate.setDn(uid);
return this.persons.save(toUpdate);
}
@PutMapping("/{uid}/password")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public void updatePassword(@PathVariable("uid") Name uid, @RequestBody Attributes attributes) {
Attribute password = attributes.get("userPassword");
this.ldap.modify(uid)
.attributes(new ModificationItem(DirContextOperations.REPLACE_ATTRIBUTE, password))
.execute();
}
@DeleteMapping("/{uid}")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public void delete(@PathVariable("uid") Name uid) {
this.persons.deleteById(uid);
}
}

View File

@@ -0,0 +1,30 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example;
import javax.naming.Name;
import org.springframework.data.ldap.repository.LdapRepository;
import org.springframework.ldap.NameNotFoundException;
public interface PersonRepository extends LdapRepository<Person> {
default Person findByDn(Name dn) {
return findById(dn).orElseThrow(() -> new NameNotFoundException("user not found"));
}
}

View File

@@ -0,0 +1,34 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Hello application.
*
* @author Joe Grandja
*/
@SpringBootApplication
public class SecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityApplication.class, args);
}
}

View File

@@ -0,0 +1,89 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Role;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.LdapClient;
import org.springframework.ldap.core.support.BaseLdapPathContextSource;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.ldap.DefaultSpringSecurityContextSource;
import org.springframework.security.ldap.authentication.BindAuthenticator;
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;
import org.springframework.security.ldap.authentication.LdapAuthenticator;
import org.springframework.security.ldap.server.UnboundIdContainer;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;
@Configuration(proxyBeanMethods = false)
@EnableMethodSecurity
public class SecurityConfig {
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static RoleHierarchy roles() {
return RoleHierarchyImpl.withDefaultRolePrefix().role("ADMIN").implies("USER").build();
}
@Bean
SecurityFilterChain http(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((requests) -> requests.anyRequest().authenticated())
.httpBasic(withDefaults())
.csrf((csrf) -> csrf.disable());
return http.build();
}
@Bean
UnboundIdContainer ldapContainer() {
UnboundIdContainer container = new UnboundIdContainer("dc=springframework,dc=org", "classpath:users.ldif");
container.setPort(0);
return container;
}
@Bean
ContextSource contextSource(UnboundIdContainer container) {
int port = container.getPort();
return new DefaultSpringSecurityContextSource("ldap://localhost:" + port + "/dc=springframework,dc=org");
}
@Bean
BindAuthenticator authenticator(BaseLdapPathContextSource contextSource) {
BindAuthenticator authenticator = new BindAuthenticator(contextSource);
authenticator.setUserDnPatterns(new String[] { "uid={0},ou=people" });
return authenticator;
}
@Bean
LdapAuthenticationProvider authenticationProvider(LdapAuthenticator authenticator, LdapClient ldap) {
LdapAuthenticationProvider provider = new LdapAuthenticationProvider(authenticator);
provider.setUserDetailsContextMapper(new PersonContextMapper(ldap));
return provider;
}
@Bean
LdapClient ldapClient(ContextSource contextSource) {
return LdapClient.create(contextSource);
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example;
import javax.naming.Name;
import javax.naming.directory.Attributes;
import com.fasterxml.jackson.databind.module.SimpleModule;
import example.ldap.AttributesDeserializer;
import example.ldap.AttributesSerializer;
import example.ldap.NameDeserializer;
import example.ldap.NameSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class WebConfig {
@Bean
public SimpleModule nameModule() {
SimpleModule module = new SimpleModule();
module.addSerializer(Name.class, new NameSerializer());
module.addDeserializer(Name.class, new NameDeserializer());
module.addSerializer(Attributes.class, new AttributesSerializer());
module.addDeserializer(Attributes.class, new AttributesDeserializer());
return module;
}
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example.ldap;
import java.io.IOException;
import java.util.Map;
import javax.naming.directory.Attributes;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.springframework.ldap.core.NameAwareAttributes;
public class AttributesDeserializer extends JsonDeserializer<Attributes> {
@Override
public Attributes deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
NameAwareAttributes attributes = new NameAwareAttributes();
if (p.currentToken() == JsonToken.START_OBJECT) {
p.nextToken();
}
Map<String, Object> map = p.getCodec().readValue(p, new TypeReference<>() {
});
for (Map.Entry<String, Object> entry : map.entrySet()) {
attributes.put(entry.getKey(), entry.getValue());
}
return attributes;
}
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example.ldap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.naming.directory.Attributes;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.ldap.core.NameAwareAttribute;
import org.springframework.ldap.core.NameAwareAttributes;
import org.springframework.util.CollectionUtils;
public class AttributesSerializer extends JsonSerializer<Attributes> {
@Override
public void serialize(Attributes value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (!(value instanceof NameAwareAttributes attributes)) {
serializers.defaultSerializeValue(value, gen);
return;
}
Iterator<NameAwareAttribute> iterator = CollectionUtils.toIterator(attributes.getAll());
while (iterator.hasNext()) {
NameAwareAttribute attribute = iterator.next();
if (attribute.size() == 0) {
serializers.defaultSerializeField(attribute.getID(), null, gen);
}
else if (attribute.size() == 1) {
serializers.defaultSerializeField(attribute.getID(), attribute.get(), gen);
}
else {
List<Object> mapElement = new ArrayList<>();
attribute.forEach(mapElement::add);
serializers.defaultSerializeField(attribute.getID(), mapElement, gen);
}
}
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example.ldap;
import javax.naming.NamingException;
import org.springframework.ldap.core.ContextMapper;
import org.springframework.ldap.core.DirContextOperations;
public interface DirContextOperationsMapper<T> extends ContextMapper<T> {
@Override
default T mapFromContext(Object o) throws NamingException {
return mapFromDirContextOperations((DirContextOperations) o);
}
T mapFromDirContextOperations(DirContextOperations source) throws NamingException;
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example.ldap;
import java.io.IOException;
import javax.naming.Name;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.springframework.ldap.support.LdapUtils;
public class NameDeserializer extends JsonDeserializer<Name> {
@Override
public Name deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
if (p.currentToken() == JsonToken.START_OBJECT) {
p.nextToken();
}
String value = p.getCodec().readValue(p, String.class);
return LdapUtils.newLdapName(value);
}
}

View File

@@ -0,0 +1,43 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example.ldap;
import java.util.Locale;
import javax.naming.Name;
import org.springframework.format.Formatter;
import org.springframework.lang.NonNull;
import org.springframework.ldap.support.LdapUtils;
import org.springframework.stereotype.Component;
@Component
public class NameFormatter implements Formatter<Name> {
@Override
@NonNull
public String print(@NonNull Name object, @NonNull Locale locale) {
return object.toString();
}
@Override
@NonNull
public Name parse(@NonNull String text, @NonNull Locale locale) {
return LdapUtils.newLdapName(text);
}
}

View File

@@ -0,0 +1,32 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example.ldap;
import org.springframework.http.ResponseEntity;
import org.springframework.ldap.NameNotFoundException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class NameNotFoundHandler {
@ExceptionHandler(NameNotFoundException.class)
public ResponseEntity<?> notFound() {
return ResponseEntity.notFound().build();
}
}

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example.ldap;
import java.io.IOException;
import javax.naming.Name;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class NameSerializer extends JsonSerializer<Name> {
@Override
public void serialize(Name name, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
serializerProvider.defaultSerializeValue(name.toString(), jsonGenerator);
}
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example.security;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.security.authorization.AuthorizationResult;
import org.springframework.security.authorization.method.MethodAuthorizationDeniedHandler;
import org.springframework.stereotype.Component;
@Component
public class NullMethodAuthorizationDeniedHandler implements MethodAuthorizationDeniedHandler {
@Override
public Object handleDeniedInvocation(MethodInvocation methodInvocation, AuthorizationResult authorizationResult) {
return null;
}
}

View File

@@ -0,0 +1 @@
spring.jackson.default-property-inclusion=non_null

View File

@@ -0,0 +1,65 @@
dn: ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: groups
dn: ou=people,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: people
dn: uid=user,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: User User
sn: User
uid: user
userPassword: password
dn: uid=may,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: May Bea
sn: May
uid: may
userPassword: later
dn: uid=hal,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Hal 2000
sn: Hal
uid: hal
userPassword: sorrydave
dn: uid=dante,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Dante Alvarez
sn: Alvarez
uid: dante
userPassword: secret
dn: cn=developers,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfUniqueNames
cn: developers
ou: developer
uniqueMember: uid=dante,ou=people,dc=springframework,dc=org
uniqueMember: uid=may,ou=people,dc=springframework,dc=org
dn: cn=managers,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfUniqueNames
cn: managers
ou: manager
uniqueMember: uid=hal,ou=people,dc=springframework,dc=org
uniqueMember: uid=may,ou=people,dc=springframework,dc=org

View File

@@ -0,0 +1,166 @@
/*
* Copyright 2002-2024 the original author or 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.
*/
package example;
import java.util.List;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.ldap.support.LdapUtils;
import org.springframework.security.ldap.server.UnboundIdContainer;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* @author Rob Winch
*/
@SpringBootTest
@AutoConfigureMockMvc
public class SecurityApplicationTests {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper mapper;
@Autowired
UnboundIdContainer container;
@BeforeEach
void setup() {
this.container.start();
}
@AfterEach
void teardown() {
this.container.stop();
}
@Test
@WithMockUser
void authenticatedPersonsThenOk() throws Exception {
// @formatter:off
String json = this.mockMvc.perform(get("/people"))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
List<Person> people = this.mapper.readValue(json, new TypeReference<>() { });
assertThat(people).hasSize(4)
.extracting(Person::getUsername).containsExactlyInAnyOrder("user", "may", "hal", "dante");
assertThat(people)
.extracting(Person::getName).containsOnlyNulls();
// @formatter:on
}
@Test
@WithMockUser(roles = "ADMIN")
void adminAuthenticatedPersonsThenOk() throws Exception {
// @formatter:off
String json = this.mockMvc.perform(get("/people"))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
List<Person> people = this.mapper.readValue(json, new TypeReference<>() { });
assertThat(people).hasSize(4)
.extracting(Person::getUsername).containsExactlyInAnyOrder("user", "may", "hal", "dante");
assertThat(people)
.extracting(Person::getName).containsExactlyInAnyOrder(
"User User", "May Bea", "Hal 2000", "Dante Alvarez");
// @formatter:on
}
@Test
void basicAuthenticatedPersonsThenOk() throws Exception {
// @formatter:off
String json = this.mockMvc.perform(get("/people").with(httpBasic("dante", "secret")))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
List<Person> people = this.mapper.readValue(json, new TypeReference<>() { });
assertThat(people).hasSize(4)
.extracting(Person::getUsername).containsExactlyInAnyOrder("user", "may", "hal", "dante");
assertThat(people)
.extracting(Person::getName).containsOnlyNulls();
// @formatter:on
}
@Test
void basicAdminAuthenticatedPersonsThenOk() throws Exception {
// @formatter:off
String json = this.mockMvc.perform(get("/people").with(httpBasic("may", "later")))
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
List<Person> people = this.mapper.readValue(json, new TypeReference<>() { });
assertThat(people).hasSize(4)
.extracting(Person::getUsername).containsExactlyInAnyOrder("user", "may", "hal", "dante");
assertThat(people)
.extracting(Person::getName).containsExactlyInAnyOrder(
"User User", "May Bea", "Hal 2000", "Dante Alvarez");
// @formatter:on
}
@Test
void meThenCurrentPerson() throws Exception {
String json = this.mockMvc.perform(get("/people/me").with(httpBasic("user", "password")))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
Person person = this.mapper.readValue(json, Person.class);
assertThat(person.getUsername()).isEqualTo("user");
}
@Test
@WithMockUser(roles = "ADMIN")
void partiallyUpdatePersonThenUpdated() throws Exception {
Person person = new Person("dante");
person.setDn(LdapUtils.newLdapName("uid=dante,ou=people"));
person.setUsername("ari");
String json = this.mapper.writeValueAsString(person);
String updated = this.mockMvc
.perform(put("/people/" + person.getDn()).content(json).contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
person = this.mapper.readValue(updated, Person.class);
assertThat(person.getUsername()).isEqualTo("ari");
assertThat(person.getDn().toString()).isEqualTo("uid=ari,ou=people");
}
@Test
@WithMockUser(roles = "ADMIN")
void deletePersonThenRemoved() throws Exception {
String dn = "uid=hal,ou=people";
this.mockMvc.perform(delete("/people/" + dn)).andExpect(status().isOk());
this.mockMvc.perform(get("/people/" + dn)).andExpect(status().isNotFound());
}
}