commit 533bd6ad0bb315f8b548b9b89520b47d792c92d6 Author: John Ahlroos Date: Sat Aug 16 16:04:25 2025 +0000 Initial implementation diff --git a/.gitea/workflows/release.yaml b/.gitea/workflows/release.yaml new file mode 100644 index 0000000..e548082 --- /dev/null +++ b/.gitea/workflows/release.yaml @@ -0,0 +1,38 @@ +name: Build & Release +on: + push: + tags: + - '[0-9]+.[0-9]+.[0-9]+' + +env: + ORG_GRADLE_PROJECT_BUILD_VERSION: ${{ gitea.ref_name }} + ORG_GRADLE_PROJECT_DEVSOAP_DEPLOY_TOKEN: ${{ secrets.DEVSOAP_DEPLOY_TOKEN }} + RUNNER_TOOL_CACHE: /toolcache + +jobs: + release-library: + runs-on: node20 + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + ssh-key: ${{ secrets.SSH_JOHN_PRIVATE_KEY }} + - name: Configure Java project + uses: actions/setup-java@v4 + with: + distribution: 'temurin' + java-version: '21' + cache: 'gradle' + - name: Cache Java dependencies + uses: actions/cache@v4 + env: + cache-name: cache-java-dependencies + with: + path: ~/.gradle + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/build.gradle','**/settings.gradle') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + - name: Upload to Devsoap Code + run: ./gradlew publishMavenJavaPublicationToDSCodeRepository \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..835e8dc --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.gradle +.idea +build \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c2b425c --- /dev/null +++ b/LICENSE @@ -0,0 +1,392 @@ +Attribution-NoDerivatives 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + + +======================================================================= + +Creative Commons Attribution-NoDerivatives 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-NoDerivatives 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + c. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + d. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + e. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + f. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + g. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + h. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + i. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + j. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce and reproduce, but not Share, Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material, You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + For the avoidance of doubt, You do not have permission under + this Public License to Share Adapted Material. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database, provided You do not Share + Adapted Material; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..43ad426 --- /dev/null +++ b/README.md @@ -0,0 +1,30 @@ +# Registration API Provider + +Keycloak Provider for performing realm registration via REST API. After registration +the user is automatically signed in and redirected to a customizable target URI. + +Supported are both HTTP Form requests and XHR requests. + +![Screenshot](docs/screenshot.png) + +## How to install this provider + +To install the provider you will need to aquire the JAR file of the provider. You can either +do that by downloading it from the repository artifacts or building it yourself (see build instructions below.). + +Once you have the JAR file put it in the ``/opt/keycloak/providers`` folder of Keycloak and restart Keycloak. + +The end-point demo form will be accessible under ``/realms/your-realm/register``. + +## How to build this provider + +To use this provider in Keycloak run the following command: + +Unix/Mac: `./gradlew jar` +Windows: `gradlew.bat jar` + +Then copy the jar from `build/libs/` folder into your Keycloak `/opt/keycloak/providers` +folder and restart Keycloak. + +A demo [docker-compose.yml](docker-compose.yml) file has been provided in the +repository as an example. \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..fb0f376 --- /dev/null +++ b/build.gradle @@ -0,0 +1,42 @@ +/** + * Copyright (C) 2025 John Ahlroos + * + * 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. + */ +plugins { + id 'java-library' + id 'maven-publish' +} + +group = 'com.devsoap' +version = findProperty('BUILD_VERSION') ?: 'latest' + +repositories { + mavenCentral() + maven { url "https://code.devsoap.com/api/packages/john/maven" } +} + +dependencies { + compileOnly "org.keycloak:keycloak-services:${keycloakVersion}" + compileOnly "org.keycloak:keycloak-server-spi:${keycloakVersion}" + compileOnly "org.keycloak:keycloak-core:${keycloakVersion}" + +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +apply from: 'publish.gradle' \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..12d42bf --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,33 @@ +services: + + keycloak: + image: quay.io/keycloak/keycloak:26.2.5 + command: "--verbose start-dev" + ports: + - 8080:8080 + depends_on: + - keycloakdb + volumes: + - ./build/libs:/opt/keycloak/providers:ro + environment: + KC_DB: postgres + KC_DB_URL: jdbc:postgresql://keycloakdb:5432/keycloak + KC_DB_USERNAME: keycloak + KC_DB_PASSWORD: password + KC_LOG_LEVEL: info + KC_BOOTSTRAP_ADMIN_USERNAME: admin + KC_BOOTSTRAP_ADMIN_PASSWORD: admin + + keycloakdb: + image: postgres:15 + volumes: + - postgres_data:/var/lib/postgresql/data + environment: + POSTGRES_DB: keycloak + POSTGRES_USER: keycloak + POSTGRES_PASSWORD: password + ports: + - 5432:5432 + +volumes: + postgres_data: \ No newline at end of file diff --git a/docs/screenshot.png b/docs/screenshot.png new file mode 100644 index 0000000..7d859ac Binary files /dev/null and b/docs/screenshot.png differ diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..93cfb47 --- /dev/null +++ b/gradle.properties @@ -0,0 +1 @@ +keycloakVersion=26.2.5 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..9bbc975 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..37f853b --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..faf9300 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/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\n' "$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, 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/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +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 diff --git a/publish.gradle b/publish.gradle new file mode 100644 index 0000000..4e1fc17 --- /dev/null +++ b/publish.gradle @@ -0,0 +1,70 @@ +/** + Copyright (c) 2025 John Ahlroos + + Creative Commons Attribution-NoDerivatives 4.0 International Public License + + By exercising the Licensed Rights (defined below), You accept and agree + to be bound by the terms and conditions of this Creative Commons + Attribution-NoDerivatives 4.0 International Public License ("Public + License"). To the extent this Public License may be interpreted as a + contract, You are granted the Licensed Rights in consideration of Your + acceptance of these terms and conditions, and the Licensor grants You + such rights in consideration of benefits the Licensor receives from + making the Licensed Material available under these terms and + conditions. + + Refer to LICENSE file or https://creativecommons.org/licenses/by-nd/4.0 for full license. + */ + +ext { + devsoapToken = findProperty("DEVSOAP_DEPLOY_TOKEN") as String +} + +publishing { + repositories { + maven { + name = "DSCode" + url = uri("https://code.devsoap.com/api/packages/john/maven") + credentials(HttpHeaderCredentials) { + name = "Authorization" + value = "token ${devsoapToken}" + } + authentication { + header(HttpHeaderAuthentication) + } + } + } + publications { + mavenJava(MavenPublication) { + from components.java + pom { + groupId = 'com.devsoap' + name = 'keycloak-rest-registration' + description = 'Keycloak Provider for registering via REST API' + url = 'https://code.devsoap.com/john/keycloak-rest-registration' + + licenses { + license { + name = 'Apache 2.0' + url = 'http://www.apache.org/licenses/LICENSE-2.0' + } + } + + scm { + url = 'https://code.devsoap.com/john/keycloak-rest-registration' + connection = 'scm:git://code.devsoap.com/john/keycloak-rest-registration.git' + developerConnection = 'scm:git://code.devsoap.com/john/keycloak-rest-registration.git' + } + + developers { + developer { + id = 'john' + name = 'John Ahlroos' + email = 'john@devsoap.com' + organizationUrl = 'https://devsoap.com' + } + } + } + } + } +} \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..37adfbe --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "keycloak-rest-registration" \ No newline at end of file diff --git a/src/main/java/com/devsoap/keycloak/RegistrationResourceProvider.java b/src/main/java/com/devsoap/keycloak/RegistrationResourceProvider.java new file mode 100644 index 0000000..427a2b7 --- /dev/null +++ b/src/main/java/com/devsoap/keycloak/RegistrationResourceProvider.java @@ -0,0 +1,180 @@ +/** + Copyright (c) 2025 John Ahlroos + + Creative Commons Attribution-NoDerivatives 4.0 International Public License + + By exercising the Licensed Rights (defined below), You accept and agree + to be bound by the terms and conditions of this Creative Commons + Attribution-NoDerivatives 4.0 International Public License ("Public + License"). To the extent this Public License may be interpreted as a + contract, You are granted the Licensed Rights in consideration of Your + acceptance of these terms and conditions, and the Licensor grants You + such rights in consideration of benefits the Licensor receives from + making the Licensed Material available under these terms and + conditions. + + Refer to LICENSE file or https://creativecommons.org/licenses/by-nd/4.0 for full license. + */ +package com.devsoap.keycloak; + +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.MediaType; +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.UriBuilder; +import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody; +import org.jboss.logging.Logger; +import org.keycloak.authentication.AuthenticationProcessor; +import org.keycloak.events.EventBuilder; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.UserSessionModel; +import org.keycloak.services.managers.AuthenticationManager; +import org.keycloak.services.resource.RealmResourceProvider; +import org.keycloak.services.validation.Validation; +import org.keycloak.theme.FreeMarkerException; +import org.keycloak.theme.Theme; +import org.keycloak.theme.freemarker.FreeMarkerProvider; +import org.keycloak.userprofile.UserProfileContext; +import org.keycloak.userprofile.UserProfileProvider; +import org.keycloak.userprofile.ValidationException; +import org.keycloak.utils.StringUtil; + +import java.io.IOException; +import java.util.*; +import java.util.stream.Collectors; + +/** + * Adds a new registration end-point on every realm + * + * /realms/{realm}/register + */ +public class RegistrationResourceProvider implements RealmResourceProvider { + + private static final Logger LOGGER = Logger.getLogger(RegistrationResourceProvider.class); + + private final KeycloakSession session; + + public RegistrationResourceProvider(KeycloakSession session) { + this.session = session; + } + + @GET + @Path("") + @Consumes(MediaType.WILDCARD) + @Produces(MediaType.TEXT_HTML) + public Response registerForm() { + try { + var theme = session.theme().getTheme(Theme.Type.LOGIN); + var freeMarkerUtil = session.getProvider(FreeMarkerProvider.class); + var realm = session.getContext().getRealm().getName(); + + var params = new HashMap(); + params.put("realm", realm); + params.put("registerAction", "/realms/%s/register".formatted(realm)); + return Response + .ok(freeMarkerUtil.processTemplate(params, "register-api-demo.ftl", theme)) + .build(); + } catch (FreeMarkerException e) { + LOGGER.error("Failed to process template register.ftl", e); + return Response.serverError().build(); + } catch (IOException e) { + LOGGER.error("Failed to read theme common", e); + return Response.serverError().build(); + } + } + + @OPTIONS + @Path("") + @Consumes(MediaType.WILDCARD) + public Response registerOptions() { + return Response.ok().build(); + } + + @POST + @Path("") + @Consumes(MediaType.APPLICATION_FORM_URLENCODED) + public Response registerForm(MultivaluedMap formParams) { + return registerJSON(formParams.entrySet().stream() + .collect(Collectors.toMap( + Map.Entry::getKey, + e -> formParams.getFirst(e.getKey())))); + } + + @POST + @Path("") + @Consumes(MediaType.APPLICATION_JSON) + public Response registerJSON(@RequestBody Map attributes) { + try { + + // Validate profile + var profileProvider = session.getProvider(UserProfileProvider.class); + var profile = profileProvider.create(UserProfileContext.REGISTRATION, attributes); + profile.validate(); + + // Create profile + var user = profile.create(); + user.setEnabled(true); + + // Create user session + var context = session.getContext(); + var realm = context.getRealm(); + var clientConnection = context.getConnection(); + var userSession = session.sessions().createUserSession( + null, + realm, + user, + user.getUsername(), + clientConnection.getRemoteAddr(), + "REST", + false, + UUID.randomUUID().toString(), + user.getId(), + UserSessionModel.SessionPersistenceState.PERSISTENT + ); + session.getContext().setUserSession(userSession); + + var clientId = Optional.ofNullable(attributes.get("client")).map(Object::toString); + if (clientId.isPresent() && !StringUtil.isBlank(clientId.get())) { + // Create active Keycloak session (Log user in) + var client = session.clients().getClientByClientId(realm, clientId.get()); + var rootAuthSession = session.authenticationSessions().createRootAuthenticationSession(realm); + var authSession = rootAuthSession.createAuthenticationSession(client); + authSession.setAuthenticatedUser(user); + + var event = new EventBuilder(realm, session, clientConnection); + AuthenticationProcessor.attachSession(authSession, userSession, session, realm, clientConnection, event); + AuthenticationManager.createLoginCookie(session, realm, user, userSession, context.getUri(), clientConnection); + } + + var redirectUri = Optional.ofNullable(attributes.get("redirectUri")).map(Object::toString); + if (redirectUri.isPresent()) { + var uri = UriBuilder.fromUri(redirectUri.get()).build(); + return Response.status(Response.Status.SEE_OTHER).location(uri).build(); + } + + return Response + .status(Response.Status.CREATED) + .header("Content-Type", "application/json") + .entity(user) + .build(); + + } catch (ValidationException ve) { + var errors = Validation.getFormErrorsFromValidation(ve.getErrors()); + return Response + .status(422) + .header("Content-Type", "application/json") + .entity(new ErrorResponse("validation-error", "Keycloak Constraint violation", errors)) + .build(); + } + } + + @Override + public Object getResource() { + return this; + } + + @Override + public void close() {} + + public record ErrorResponse(String type, String message, List errors) {} +} \ No newline at end of file diff --git a/src/main/java/com/devsoap/keycloak/RegistrationResourceProviderFactory.java b/src/main/java/com/devsoap/keycloak/RegistrationResourceProviderFactory.java new file mode 100644 index 0000000..180c1ba --- /dev/null +++ b/src/main/java/com/devsoap/keycloak/RegistrationResourceProviderFactory.java @@ -0,0 +1,48 @@ +/** + Copyright (c) 2025 John Ahlroos + + Creative Commons Attribution-NoDerivatives 4.0 International Public License + + By exercising the Licensed Rights (defined below), You accept and agree + to be bound by the terms and conditions of this Creative Commons + Attribution-NoDerivatives 4.0 International Public License ("Public + License"). To the extent this Public License may be interpreted as a + contract, You are granted the Licensed Rights in consideration of Your + acceptance of these terms and conditions, and the Licensor grants You + such rights in consideration of benefits the Licensor receives from + making the Licensed Material available under these terms and + conditions. + + Refer to LICENSE file or https://creativecommons.org/licenses/by-nd/4.0 for full license. + */ +package com.devsoap.keycloak; + +import org.keycloak.Config; +import org.keycloak.models.KeycloakSession; +import org.keycloak.models.KeycloakSessionFactory; +import org.keycloak.services.resource.RealmResourceProvider; +import org.keycloak.services.resource.RealmResourceProviderFactory; + +public class RegistrationResourceProviderFactory implements RealmResourceProviderFactory { + + public static final String PROVIDER_ID = "register"; + + @Override + public RealmResourceProvider create(KeycloakSession session) { + return new RegistrationResourceProvider(session); + } + + @Override + public void init(Config.Scope config) {} + + @Override + public void postInit(KeycloakSessionFactory factory) {} + + @Override + public String getId() { + return PROVIDER_ID; + } + + @Override + public void close() {} +} \ No newline at end of file diff --git a/src/main/resources/META-INF/services/org.keycloak.services.resource.RealmResourceProviderFactory b/src/main/resources/META-INF/services/org.keycloak.services.resource.RealmResourceProviderFactory new file mode 100644 index 0000000..e421fa1 --- /dev/null +++ b/src/main/resources/META-INF/services/org.keycloak.services.resource.RealmResourceProviderFactory @@ -0,0 +1 @@ +com.devsoap.keycloak.RegistrationResourceProviderFactory \ No newline at end of file diff --git a/src/main/resources/theme-resources/templates/register-api-demo.ftl b/src/main/resources/theme-resources/templates/register-api-demo.ftl new file mode 100644 index 0000000..9fbf618 --- /dev/null +++ b/src/main/resources/theme-resources/templates/register-api-demo.ftl @@ -0,0 +1,92 @@ + + + + Register on ${realm} + + + + + + +
+
Demo
+
+

Registration example on ${realm}

+
+
+

+ This is an example of how you can write an external HTML form for registering a + new user on a Keycloak Realm using the provided REST API end-point. The form + does not need to be a Keycloak template nor does it need to be hosted on the same + server as Keycloak. +

+

+ With this plugin every realm will have a REST end-point at +

POST /realms/<realmname>/register
+ to which you can do a HTTP request to register a new user.
+ After the user is created on Keycloak he will be automatically logged in and have an + active Keycloak session. +

+

+ You can test this with the registration form below: +

+
+ +
+ + \ No newline at end of file