Skip to content

Commit

Permalink
Added user migration provider
Browse files Browse the repository at this point in the history
  • Loading branch information
dyohan9 committed Dec 22, 2020
1 parent 8e968db commit 96528a7
Show file tree
Hide file tree
Showing 28 changed files with 2,681 additions and 0 deletions.
15 changes: 15 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
**/target/
/target/
*/target/*
.classpath
.project
.settings
.idea

# Package Files #
*.jar
*.war
*.ear

*.iml
*.idea
9 changes: 9 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,13 @@
FROM quay.io/keycloak/keycloak:11.0.3

USER root

COPY ./keycloak-user-migration/ /project
RUN cd /project && ./mvnw clean package

FROM quay.io/keycloak/keycloak:11.0.3
USER root

COPY --from=0 /project/target/*.jar /opt/jboss/keycloak/standalone/deployments/app.jar
COPY ./themes/ilhasoft/ /opt/jboss/keycloak/themes/ilhasoft/
#COPY ./standalone.xml /opt/jboss/keycloak/standalone/configuration/standalone.xml
118 changes: 118 additions & 0 deletions keycloak-user-migration/.mvn/wrapper/MavenWrapperDownloader.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* Copyright 2007-present 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.
*/

import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;

public class MavenWrapperDownloader {

private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";

/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";

/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";

/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";

public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());

// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if (mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if (mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);

File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if (!outputFile.getParentFile().exists()) {
if (!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}

private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}

}
2 changes: 2 additions & 0 deletions keycloak-user-migration/.mvn/wrapper/maven-wrapper.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
159 changes: 159 additions & 0 deletions keycloak-user-migration/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
# Keycloak user migration example

![Code Soapbox logo](readme-images/logo.png)

[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=keycloak-user-migration&metric=alert_status)](https://sonarcloud.io/dashboard?id=keycloak-user-migration)
[![Maintainability Rating](https://sonarcloud.io/api/project_badges/measure?project=keycloak-user-migration&metric=sqale_rating)](https://sonarcloud.io/dashboard?id=keycloak-user-migration)
[![Reliability Rating](https://sonarcloud.io/api/project_badges/measure?project=keycloak-user-migration&metric=reliability_rating)](https://sonarcloud.io/dashboard?id=keycloak-user-migration)
[![Security Rating](https://sonarcloud.io/api/project_badges/measure?project=keycloak-user-migration&metric=security_rating)](https://sonarcloud.io/dashboard?id=keycloak-user-migration)
[![Vulnerabilities](https://sonarcloud.io/api/project_badges/measure?project=keycloak-user-migration&metric=vulnerabilities)](https://sonarcloud.io/dashboard?id=keycloak-user-migration)
[![Bugs](https://sonarcloud.io/api/project_badges/measure?project=keycloak-user-migration&metric=bugs)](https://sonarcloud.io/dashboard?id=keycloak-user-migration)
[![Coverage](https://sonarcloud.io/api/project_badges/measure?project=keycloak-user-migration&metric=coverage)](https://sonarcloud.io/dashboard?id=keycloak-user-migration)

## Introduction

This is a user migration plugin for Keycloak. Read more at:

https://codesoapbox.dev/keycloak-user-migration

## Compatibility

| Keycloak Version | Commit |
|------------------|--------------------------------------------------------------------------------------------------------------------------------------------------|
| 11.X | Current |
| 9.X | [c9c64162b91cedc29d8bf360c3df50b69fdb4c6b](https://github.com/daniel-frak/keycloak-user-migration/tree/c9c64162b91cedc29d8bf360c3df50b69fdb4c6b) |

## Prerequisites - REST endpoints in the legacy system

You must provide two REST endpoints (GET and POST) in your legacy authentication system under the URI `${restClientUri
}/{$username}`, where `${restClientUri}` is a configurable base URL for the endpoints and `{$username}` is the
username of the user that is attempting to sign in.

### GET
The GET request will have to return user data as a JSON response in the form:
```json
{
"id": "string",
"username": "string",
"email": "string",
"firstName": "string",
"lastName": "string",
"enabled": "boolean",
"emailVerified": "boolean",
"attributes": {
"key": ["value"]
},
"roles": ["string"],
"groups": ["string"]
}
```

Any HTTP status other than `200` will be interpreted as the user not having been found.

The `id` attribute in the above response is optional. If it's not set Keycloak will generate a new user id automatically.

### POST
The POST request is for password validation. It will have to accept the following body:
```json
{
"password": "string"
}
```

...And return HTTP status 200 if the password is correct. Any other response will be treated as invalid credentials.

### Example REST client behavior

Let's assume we have configured the legacy REST service under the URL `http://www.old-legacy-system.com/auth`.

If a user with the username `bob` and the password `password123` tries to log in through Keycloak for the first time
(giving correct credentials), a GET request will be performed to `http://www.old-legacy-system.com/auth/bob`.
The response might look like this:
```json
{
"username": "bob",
"email": "[email protected]",
"firstName": "Bob",
"lastName": "Smith",
"enabled": "true",
"emailVerified": "true",
"attributes": {
"position": ["rockstar-developer"],
"likes": ["cats", "dogs", "cookies"]
},
"roles": ["admin"],
"groups": ["migrated_users"]
}
```

As the user has been found, a POST request will be performed to `http://www.old-legacy-system.com/auth/bob`, with
the body:
```json
{
"password": "password123"
}
```

As this is the correct password, the user will be logged in. In the background, his information will be migrated to
Keycloak.

## Launching and configuring the example
1. Navigate to `./docker`
2. Execute `docker-compose up`
3. Open `http://localhost:8024/auth/admin/` in a browser
4. Log in with the credentials:
* User: `admin`
* Password: `admin`
5. Navigate to "User federation":

![Sidebar](readme-images/sidebar.png)

6. Choose "User migration using a REST client" from the "Add provider..." dropdown:

![User federation dropdown](readme-images/user-federation.png)

7. Provide the legacy system endpoint URI in the "Rest client URI" field:

![Rest client URI input](readme-images/field_rest_client_uri.png)

8. Click "save":

![Save button](readme-images/save_btn.png)

User migration should now work - Keycloak will recognize all users from your legacy authentication system and migrate
them automatically.

## Optional - additional configuration

Additional configuration options are available for fine-tuning the migration.

![Additional configuration](readme-images/config.png)

### API Token

The migration endpoint can be secured with an API token. The configured value will be sent as a bearer token in the authorization header.

If the configured token value is set to `SECRET_API_TOKEN` when making the request to the migration endpoints, the rest client will send the following authorization header:
```
Authorization: Bearer SECRET_API_TOKEN
```

### Legacy role conversion

If role names in Keycloak do not perfectly match those in the legacy system, you can configure the provider to
automatically map legacy roles to Keycloak roles, by specifying the mapping in the format `legacyRole:keycloakRole`.

### Migrate unmapped roles

This switch can be toggled to decide whether roles which are not defined in the legacy role conversion map should be
migrated anyway or simply ignored.

### Group role conversion

If group names in Keycloak do not perfectly match those in the legacy system, you can configure the provider to
automatically map legacy groups to Keycloak groups, by specifying the mapping in the format `legacyGroup:keycloakGroup`.

### Migrate unmapped groups

This switch can be toggled to decide whether groups which are not defined in the legacy group conversion map should be
migrated anyway or simply ignored.
Loading

0 comments on commit 96528a7

Please sign in to comment.