diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4b358a4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +/nbactions.xml +/nbproject +/target +/nb-configuration.xml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..7cc5239 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,4 @@ +language: java +dist: xenial +jdk: + - openjdk11 diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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 + + http://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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4ce6f97 --- /dev/null +++ b/README.md @@ -0,0 +1,5 @@ +# Spring Security LTPA2 - Web Reactive Sample + +[![Build Status](https://travis-ci.com/sephiroth-j/spring-security-ltpa2-reactive-sample.svg?branch=master)](https://travis-ci.com/sephiroth-j/spring-security-ltpa2-reactive-sample) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) + +Sample project for Web Reactive with Spring Boot 2.2 to demonstrate the use of [spring-security-ltpa2](https://github.com/sephiroth-j/spring-security-ltpa2-core). It uses [an embedded LDAP](https://docs.spring.io/spring-boot/docs/2.2.x/reference/htmlsingle/#boot-features-ldap-embedded) as user storage and [EhCache 3](https://www.ehcache.org/) to cache the look-up result with [`@Cacheable`](https://docs.spring.io/spring-boot/docs/2.2.x/reference/htmlsingle/#boot-features-caching). diff --git a/lombok.config b/lombok.config new file mode 100644 index 0000000..df71bb6 --- /dev/null +++ b/lombok.config @@ -0,0 +1,2 @@ +config.stopBubbling = true +lombok.addLombokGeneratedAnnotation = true diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..4909b65 --- /dev/null +++ b/pom.xml @@ -0,0 +1,150 @@ + + + 4.0.0 + + de.sephiroth-j + spring-security-ltpa2-reactive-sample + Spring Security LTPA2 - Sample Project for Web Reactive + Spring Boot sample application to spring-security-ltpa2. + http://www.sephiroth-j.de/java/spring-security-ltpa2/ + 0.1.0-SNAPSHOT + 2019 + + GitHub Issues + https://github.com/sephiroth-j/spring-security-ltpa2-reactive-sample/issues + + + + Apache License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0 + + + + + org.springframework.boot + spring-boot-starter-parent + 2.2.2.RELEASE + + + + 1.8 + ${project.java.version} + UTF-8 + UTF-8 + 1.8 + 1.8 + true + 3.8.1 + [1.18.10,) + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.jacoco + jacoco-maven-plugin + 0.8.5 + + + default-prepare-agent + + prepare-agent + + + + default-report + + report + + + + + + + + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-data-ldap + + + com.unboundid + unboundid-ldapsdk + + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.security + spring-security-ldap + + + org.thymeleaf.extras + thymeleaf-extras-springsecurity5 + + + ${project.groupId} + spring-security-ltpa2 + [1.0.0,) + + + + + org.springframework.boot + spring-boot-starter-cache + + + org.ehcache + ehcache + runtime + + + + org.projectlombok + lombok + provided + + + org.springframework.boot + spring-boot-configuration-processor + true + + + org.springframework.boot + spring-boot-devtools + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + + mrepo.sephiroth-j.de + http://mrepo.sephiroth-j.de/ + + + diff --git a/src/main/java/hello/Application.java b/src/main/java/hello/Application.java new file mode 100644 index 0000000..9d757f4 --- /dev/null +++ b/src/main/java/hello/Application.java @@ -0,0 +1,31 @@ +/* + * Copyright 2019 Ronny "Sephiroth" Perinke + * + * 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 + * + * http://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 hello; + +import org.springframework.boot.WebApplicationType; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; + +@SpringBootApplication +public class Application +{ + + public static void main(String... args) + { + new SpringApplicationBuilder(Application.class).web(WebApplicationType.REACTIVE).run(args); + } + +} diff --git a/src/main/java/hello/FooController.java b/src/main/java/hello/FooController.java new file mode 100644 index 0000000..470c39b --- /dev/null +++ b/src/main/java/hello/FooController.java @@ -0,0 +1,55 @@ +/* + * Copyright 2019 Ronny "Sephiroth" Perinke + * + * 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 + * + * http://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 hello; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.annotation.AuthenticationPrincipal; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import reactor.core.publisher.Mono; + +/** + * + * @author Sephiroth + */ +@Controller +public class FooController +{ + @GetMapping(path = + { + "/", "/home" + }) + public String home() + { + return "home"; + } + + @GetMapping("/hello") + public String hello() + { + return "hello"; + } + + @PreAuthorize("hasRole('DEVELOPERS')") + @GetMapping("/secured-method") + public Mono securedMethod(@AuthenticationPrincipal UserDetails user, Model model) + { + model.addAttribute("name", user.getUsername()); + return Mono.just("securedMethod"); + } +} diff --git a/src/main/java/hello/auth/MyLdapUserDetailsManager.java b/src/main/java/hello/auth/MyLdapUserDetailsManager.java new file mode 100644 index 0000000..706a317 --- /dev/null +++ b/src/main/java/hello/auth/MyLdapUserDetailsManager.java @@ -0,0 +1,67 @@ +/* + * Copyright 2019 Ronny "Sephiroth" Perinke + * + * 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 + * + * http://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 hello.auth; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import lombok.NonNull; +import org.springframework.cache.annotation.Cacheable; +import org.springframework.ldap.core.ContextSource; +import org.springframework.security.core.userdetails.ReactiveUserDetailsService; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.ldap.userdetails.LdapUserDetailsManager; +import reactor.core.publisher.Mono; + +/** + * Example of a {@link LdapUserDetailsManager} that alters the username given in the LTPA2 token in order to map it to the LDAP scheme + * + * @author Sephiroth + */ +public class MyLdapUserDetailsManager extends LdapUserDetailsManager implements ReactiveUserDetailsService +{ + protected static final Pattern UUID_EXTRACTION_PATTERN = Pattern.compile(".+=([a-f\\-0-9]{36}),.+", Pattern.CASE_INSENSITIVE); + + public MyLdapUserDetailsManager(ContextSource contextSource) + { + super(contextSource); + } + + @Override + public UserDetails loadUserByUsername(String username) + { + return super.loadUserByUsername(extractUuid(username)); + } + + /** + * extract the UUID from the DN-String + * + * @param username + * @return the UUID or {@code username} if no UUID was found + */ + protected static String extractUuid(@NonNull final String username) + { + Matcher matcher = UUID_EXTRACTION_PATTERN.matcher(username); + return matcher.matches() ? matcher.group(1) : username; + } + + @Cacheable(cacheNames = "ldapUser", sync = true) + @Override + public Mono findByUsername(String username) + { + // simple but no good wrapper and for demo purpose only! use something like ReactiveAuthenticationManagerAdapter for production + return Mono.justOrEmpty(loadUserByUsername(username)); + } +} diff --git a/src/main/java/hello/config/WebConfig.java b/src/main/java/hello/config/WebConfig.java new file mode 100644 index 0000000..55e96fe --- /dev/null +++ b/src/main/java/hello/config/WebConfig.java @@ -0,0 +1,42 @@ +/* + * Copyright 2019 Sephiroth. + * + * 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 + * + * http://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 hello.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.config.EnableWebFlux; +import org.springframework.web.reactive.config.ViewResolverRegistry; +import org.springframework.web.reactive.config.WebFluxConfigurer; +import org.thymeleaf.spring5.view.reactive.ThymeleafReactiveViewResolver; + +/** + * + * @author Sephiroth + */ +@Configuration +@EnableWebFlux +public class WebConfig implements WebFluxConfigurer +{ + @Autowired + ThymeleafReactiveViewResolver thymeleafReactiveViewResolver; + + @Override + public void configureViewResolvers(ViewResolverRegistry registry) + { + registry.viewResolver(thymeleafReactiveViewResolver); + } + +} diff --git a/src/main/java/hello/config/WebSecurityConfig.java b/src/main/java/hello/config/WebSecurityConfig.java new file mode 100644 index 0000000..b621ede --- /dev/null +++ b/src/main/java/hello/config/WebSecurityConfig.java @@ -0,0 +1,102 @@ +/* + * Copyright 2019 Ronny "Sephiroth" Perinke + * + * 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 + * + * http://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 hello.config; + +import de.sephirothj.spring.security.ltpa2.reactive.Ltpa2AuthConverter; +import de.sephirothj.spring.security.ltpa2.reactive.Ltpa2AuthManager; +import de.sephirothj.spring.security.ltpa2.LtpaKeyUtils; +import hello.auth.MyLdapUserDetailsManager; +import java.security.GeneralSecurityException; +import java.security.PublicKey; +import javax.crypto.SecretKey; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; +import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; +import org.springframework.security.config.web.server.SecurityWebFiltersOrder; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.core.userdetails.ReactiveUserDetailsService; +import org.springframework.security.ldap.DefaultLdapUsernameToDnMapper; +import org.springframework.security.ldap.DefaultSpringSecurityContextSource; +import org.springframework.security.web.server.SecurityWebFilterChain; +import org.springframework.security.web.server.authentication.AuthenticationWebFilter; + +@Configuration +@EnableWebFluxSecurity +@EnableReactiveMethodSecurity +@EnableCaching +public class WebSecurityConfig +{ + + @Bean + public SecurityWebFilterChain springSecurityFilterChain(final ServerHttpSecurity http, final ReactiveUserDetailsService userDetailsService, AuthenticationWebFilter ltpa2AuthenticationWebFilter) + { + http + .csrf().disable() + .httpBasic().disable() + .authorizeExchange() + .pathMatchers( + "/", + "/home" + ).permitAll() + .pathMatchers("/hello").hasRole("DEVELOPERS") + // all other require any authentication + .anyExchange().authenticated() + .and() + // apply ltpa2 authentication filter + .addFilterAt(ltpa2AuthenticationWebFilter, SecurityWebFiltersOrder.AUTHENTICATION); + return http.build(); + } + + @Bean + AuthenticationWebFilter x509AuthenticationWebFilter(ReactiveUserDetailsService userDetailsService) throws GeneralSecurityException + { + final Ltpa2AuthConverter converter = new Ltpa2AuthConverter(); + converter.setSharedKey(sharedKey()); + converter.setSignerKey(signerKey()); + + final AuthenticationWebFilter webfilter = new AuthenticationWebFilter(new Ltpa2AuthManager(userDetailsService)); + webfilter.setServerAuthenticationConverter(converter); + return webfilter; + } + + @Bean + public ReactiveUserDetailsService userDetailsService() + { + final DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource("ldap://127.0.0.1:33389/dc=foo,dc=bar"); + contextSource.afterPropertiesSet(); + + MyLdapUserDetailsManager manager = new MyLdapUserDetailsManager(contextSource); + manager.setUsernameMapper(new DefaultLdapUsernameToDnMapper("ou=user", "cn")); + manager.setGroupSearchBase("ou=groups"); + + return manager; + } + + private SecretKey sharedKey() throws GeneralSecurityException + { + String testKey = "JvywHhxC+EhtUdeusbo31E5IUOEPmbMxMnKTTOB39fo="; + String testKeyPass = "test123"; + return LtpaKeyUtils.decryptSharedKey(testKey, testKeyPass); + } + + private PublicKey signerKey() throws GeneralSecurityException + { + String testSignerKey = "AOECPMDAs0o7MzQIgxZhAXJZ2BaDE3mqRZAbkbQO38CgUIgeAPEA3iWIYp+p/Ai0J4//UOml20an+AuCnDGzcFCaf3S3EAiR4cK59vl/u8TIswPIg2akh4J7qL3E/qRxN9WD945tS3h0YhJZSq7rC22wytLsxbFuKpEuYfm1i5spAQAB"; + return LtpaKeyUtils.decodePublicKey(testSignerKey); + } +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..f368dc4 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,7 @@ +spring: + main: + web-application-type: "reactive" + ldap: + embedded: + baseDn: dc=foo,dc=bar + port: 33389 diff --git a/src/main/resources/schema.ldif b/src/main/resources/schema.ldif new file mode 100644 index 0000000..3582f1e --- /dev/null +++ b/src/main/resources/schema.ldif @@ -0,0 +1,31 @@ +dn: dc=foo,dc=bar +objectclass: top +objectclass: dcObject +objectclass: organization +dc: foo +o: foo + +dn: ou=user,dc=foo,dc=bar +objectclass: top +objectclass: organizationalUnit +ou: user + +dn: cn=fae6d87c-c642-45a6-9f09-915c7fd8b08c,ou=user,dc=foo,dc=bar +objectclass: top +objectclass: person +objectclass: organizationalPerson +objectclass: inetOrgPerson +cn: Rod Johnson +sn: Johnson +uid: fae6d87c-c642-45a6-9f09-915c7fd8b08c + +dn: ou=groups,dc=foo,dc=bar +objectclass: top +objectclass: organizationalUnit +ou: groups + +dn: cn=developers,ou=groups,dc=foo,dc=bar +objectclass: top +objectclass: groupOfUniqueNames +cn: developers +uniqueMember: cn=fae6d87c-c642-45a6-9f09-915c7fd8b08c,ou=user,dc=foo,dc=bar diff --git a/src/main/resources/templates/hello.html b/src/main/resources/templates/hello.html new file mode 100644 index 0000000..8cf4d9c --- /dev/null +++ b/src/main/resources/templates/hello.html @@ -0,0 +1,10 @@ + + + + Hello World! + + +

Hello !

+ + \ No newline at end of file diff --git a/src/main/resources/templates/home.html b/src/main/resources/templates/home.html new file mode 100644 index 0000000..359d8f3 --- /dev/null +++ b/src/main/resources/templates/home.html @@ -0,0 +1,11 @@ + + + + Spring Security LTPA2 Example + + +

Welcome!

+ +

Click here to see a greeting.

+ + \ No newline at end of file diff --git a/src/main/resources/templates/securedMethod.html b/src/main/resources/templates/securedMethod.html new file mode 100644 index 0000000..df46a86 --- /dev/null +++ b/src/main/resources/templates/securedMethod.html @@ -0,0 +1,10 @@ + + + + Getting Started: Serving Web Content + + + +

+ + \ No newline at end of file diff --git a/src/test/java/hello/ApplicationTests.java b/src/test/java/hello/ApplicationTests.java new file mode 100644 index 0000000..2a47d07 --- /dev/null +++ b/src/test/java/hello/ApplicationTests.java @@ -0,0 +1,128 @@ +/* + * Copyright 2019 Ronny "Sephiroth" Perinke + * + * 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 + * + * http://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 hello; + +import de.sephirothj.spring.security.ltpa2.Ltpa2Token; +import de.sephirothj.spring.security.ltpa2.Ltpa2Utils; +import de.sephirothj.spring.security.ltpa2.LtpaKeyUtils; +import java.security.GeneralSecurityException; +import java.security.PrivateKey; +import java.time.LocalDateTime; +import javax.crypto.SecretKey; +import lombok.NonNull; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.http.HttpHeaders; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.junit.jupiter.SpringExtension; +import org.springframework.test.web.reactive.server.WebTestClient; + +import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.springSecurity; + +@ExtendWith(SpringExtension.class) +@SpringBootTest +class ApplicationTests +{ + @Autowired + private ApplicationContext context; + + private WebTestClient webTestClient; + + @BeforeEach + void setup() + { + webTestClient = WebTestClient.bindToApplicationContext(context) + .apply(springSecurity()) + .configureClient() + .build(); + } + + @Test + void accessUnsecuredResourceThenOk() + { + webTestClient.get().uri("/") + .exchange() + .expectStatus().isOk(); + } + + @Test + void accessSecuredResourceUnauthenticatedShouldBeForbidden() + { + webTestClient.get().uri("/hello") + .exchange() + .expectStatus().isUnauthorized(); + } + + @Test + void accessSecuredResourceWithInvalidAuthenticationShouldBeForbidden() throws Exception + { + webTestClient.get().uri("/hello") + .header(HttpHeaders.AUTHORIZATION, "sadfdas") + .exchange() + .expectStatus().isUnauthorized(); + } + + @Test + void accessSecuredResourceWithAuthenticationThenOk() throws Exception + { + Ltpa2Token token = createTestToken(); + + webTestClient.get().uri("/hello") + .header(HttpHeaders.AUTHORIZATION, "LtpaToken2 ".concat(encryptToken(token))) + .exchange() + .expectStatus().isOk(); + } + + @Test + void accessSecuredResourceWithCookieThenOk() throws Exception + { + Ltpa2Token token = createTestToken(); + + webTestClient.get().uri("/secured-method") + .cookie("LtpaToken2", encryptToken(token)) + .exchange() + .expectStatus().isOk(); + } + + @Test + @WithMockUser(roles = "DEVELOPERS") + void accessSecuredResourceAuthenticatedThenOk() throws Exception + { + webTestClient.get().uri("/hello") + .exchange() + .expectStatus().isOk(); + } + + private Ltpa2Token createTestToken() + { + Ltpa2Token token = new Ltpa2Token(); + token.setUser("user:LdapRegistry/CN=fae6d87c-c642-45a6-9f09-915c7fd8b08c,OU=user,DC=foo,DC=bar"); + token.setExpire(LocalDateTime.now().plusMinutes(1)); + return token; + } + + private String encryptToken(@NonNull Ltpa2Token token) throws GeneralSecurityException + { + SecretKey sharedKey = LtpaKeyUtils.decryptSharedKey(Constants.ENCRYPTED_SHARED_KEY, Constants.ENCRYPTION_PASSWORD); + PrivateKey privateKey = LtpaKeyUtils.decryptPrivateKey(Constants.ENCRYPTED_PRIVATE_KEY, Constants.ENCRYPTION_PASSWORD); + + return Ltpa2Utils.encryptToken(token, privateKey, sharedKey); + } +} diff --git a/src/test/java/hello/Constants.java b/src/test/java/hello/Constants.java new file mode 100644 index 0000000..52b1ad7 --- /dev/null +++ b/src/test/java/hello/Constants.java @@ -0,0 +1,46 @@ +/* + * Copyright 2019 Ronny "Sephiroth" Perinke + * + * 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 + * + * http://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 hello; + +import lombok.experimental.UtilityClass; + +/** + * + * @author Sephiroth + */ +@UtilityClass +public class Constants +{ + /** + * base64-encoded and encrypted private key used to sign the tokens + */ + public final String ENCRYPTED_PRIVATE_KEY = "dP4F2H1MSphvjXHFnLqc1sUYiM83Mkg5MzCQWbxya0xMLPl6lwSbC9+SuCpbHTb9Qdl1w3d5bcDf400tBnfStdtkRYSOeo9oEbXOG4RqIV0x3WZx7AyJ5D8wVIfzOjgvfdQXqNkoiatyMwptvCytyEVbWH2kj3j0gB8O2/miPsbnZqNdIRDAt4TE2YjhVagC/ZP2xxxwncLDexF8Bme7NaMtJUlGMe8Nhkb61Z52PU2FHJAF6zPaTwj+JcZ/tg63lr5wRI9hGFOb7MhBrhgm9YiBqPOT30Crl28FHtTP9pnrqiC45QxU3aXVsYFh0hXptkkK9HeTk/YWFjDPVlfg9azrgGq64wHHg3cSjV21GAE="; + + /** + * base64-encoded public key which corresponds to {@link #ENCRYPTED_PRIVATE_KEY} + */ + public final String ENCODED_PUBLIC_KEY = "AOECPMDAs0o7MzQIgxZhAXJZ2BaDE3mqRZAbkbQO38CgUIgeAPEA3iWIYp+p/Ai0J4//UOml20an+AuCnDGzcFCaf3S3EAiR4cK59vl/u8TIswPIg2akh4J7qL3E/qRxN9WD945tS3h0YhJZSq7rC22wytLsxbFuKpEuYfm1i5spAQAB"; + + /** + * base64-encoded and encrypted shared secret key used to encrypt and decrypt the tokens + */ + public final String ENCRYPTED_SHARED_KEY = "JvywHhxC+EhtUdeusbo31E5IUOEPmbMxMnKTTOB39fo="; + + /** + * password that has been used for encypting of {@link #ENCRYPTED_PRIVATE_KEY} and {@link #ENCRYPTED_SHARED_KEY} + */ + public final String ENCRYPTION_PASSWORD = "test123"; +} diff --git a/src/test/java/hello/auth/MyLdapUserDetailsManagerTest.java b/src/test/java/hello/auth/MyLdapUserDetailsManagerTest.java new file mode 100644 index 0000000..c70a471 --- /dev/null +++ b/src/test/java/hello/auth/MyLdapUserDetailsManagerTest.java @@ -0,0 +1,44 @@ +/* + * Copyright 2019 Ronny "Sephiroth" Perinke + * + * 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 + * + * http://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 hello.auth; + +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * + * @author Sephiroth + */ +class MyLdapUserDetailsManagerTest +{ + @Test + void extractUuidTestWithFullDn() + { + String username = "user:LdapRegistry/CN=fae6d87c-c642-45a6-9f09-915c7fd8b08c,OU=user,DC=foo,DC=bar"; + + assertThat(MyLdapUserDetailsManager.extractUuid(username)).isEqualTo("fae6d87c-c642-45a6-9f09-915c7fd8b08c"); + } + + @Test + void extractUuidTestWithUIDOnly() + { + String username = "fae6d87c-c642-45a6-9f09-915c7fd8b08c"; + + assertThat(MyLdapUserDetailsManager.extractUuid(username)).isEqualTo(username); + } + +} diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml new file mode 100644 index 0000000..c25977d --- /dev/null +++ b/src/test/resources/application.yml @@ -0,0 +1,17 @@ +spring: + main: + web-application-type: "reactive" + ldap: + embedded: + baseDn: dc=foo,dc=bar + port: 33389 + +logging: + level: + org: + springframework: + security: + ldap: DEBUG + hello: + auth: DEBUG + \ No newline at end of file