diff --git a/README.md b/README.md index fa27aac6c..4fafa96c4 100644 --- a/README.md +++ b/README.md @@ -142,6 +142,9 @@ SAMPLES_HOME ├── user-mgt │ ├── remote-user-mgt │ └── sample-custom-user-store-manager +|── user-migration-samples +│ └── asgardeo +│ └── external-authentication-service ├── workflow │ ├── handler │ │ └── service-provider diff --git a/user-migration-samples/README.md b/user-migration-samples/README.md new file mode 100644 index 000000000..57b82a27d --- /dev/null +++ b/user-migration-samples/README.md @@ -0,0 +1,11 @@ +# User Migration Samples + +This directory contains samples for migrating users from one identity provider to WSO2 Identity Server or Asgardeo. + +## Directory tree of Samples + +``` +SAMPLES_HOME +├── asgardeo + └── external-authentication-service +``` diff --git a/user-migration-samples/asgardeo/external-authentication-service/.devcontainer.json b/user-migration-samples/asgardeo/external-authentication-service/.devcontainer.json new file mode 100644 index 000000000..8a0177271 --- /dev/null +++ b/user-migration-samples/asgardeo/external-authentication-service/.devcontainer.json @@ -0,0 +1,4 @@ +{ + "image": "ballerina/ballerina-devcontainer:2201.8.6", + "extensions": ["WSO2.ballerina"], +} diff --git a/user-migration-samples/asgardeo/external-authentication-service/.gitignore b/user-migration-samples/asgardeo/external-authentication-service/.gitignore new file mode 100644 index 000000000..7512ebe23 --- /dev/null +++ b/user-migration-samples/asgardeo/external-authentication-service/.gitignore @@ -0,0 +1,3 @@ +target +generated +Config.toml diff --git a/user-migration-samples/asgardeo/external-authentication-service/Ballerina.toml b/user-migration-samples/asgardeo/external-authentication-service/Ballerina.toml new file mode 100644 index 000000000..32b25caf9 --- /dev/null +++ b/user-migration-samples/asgardeo/external-authentication-service/Ballerina.toml @@ -0,0 +1,8 @@ +[package] +org = "WSO2" +name = "external_authentication_service" +version = "0.1.0" +distribution = "2201.8.6" + +[build-options] +observabilityIncluded = true diff --git a/user-migration-samples/asgardeo/external-authentication-service/README.md b/user-migration-samples/asgardeo/external-authentication-service/README.md new file mode 100644 index 000000000..6d2826360 --- /dev/null +++ b/user-migration-samples/asgardeo/external-authentication-service/README.md @@ -0,0 +1,64 @@ +# External Authentication Service + +## Introduction + +On-demand silent password migration enables the seamless migration of user passwords from the legacy system to Asgardeo during login time. Prior to on-demand silent password migration, user accounts need to be bulk imported to the Asgardeo user store. In this process, both the legacy system and Asgardeo operate in parallel for a specified period of time, allowing users to access applications and services using their existing credentials stored in the legacy system. + +When a user attempts to log in to Asgardeo for the first time, Asgardeo checks whether the user's password has been migrated and if not, it initiates an external authentication process to the legacy system. Once a user is authenticated successfully with the legacy system, Asgardeo imports the user’s password into the local system. Once the password is migrated to Asgardeo, users can continue to access the application and services through Asgardeo without invoking the external legacy system. + +This sample demonstrates how to implement an external authentication service in [Ballerina](https://ballerina.io/learn/get-started/) programming language that can be used to authenticate users against a legacy system. + +> [!NOTE] +> - This guide provides a sample authentication service which satisfies only the basic functional requirement. + +> [!WARNING] +> - We recommend adding necessary logs for audit purposes when developing the REST service. However be cautious on the information you log, especially DO NOT log any sensitive information including PII. + +The sample exposes three REST API endpoints as follows: +1. `/start-authentication` (POST) - This endpoint initiates the authentication process with the legacy system. + It accepts the request, return a response with a random UUID and then start the external + authentication process. After completing the process, the authentication result is added to an in-memory + map with the generated UUID. +2. `/authentication-status` (POST) - This endpoint retrieves and returns the completed authentication result + from the in-memory map using the UUID. +3. `/authentication-status` (GET) - This endpoint returns the processing completion status. This is an open endpoint that doesn’t have any authentication. + +![External authentication service structure](resources/images/external_authentication-choreo-service.png) + +## Prerequisites + +- Your legacy authentication system (existing IdP) should provide some means to perform basic user authentication (i.e. username and password authentication). For example it could be exposing a Scim2/Me REST API endpoint that can be authenticated with username and password. +- Download [Ballerina](https://ballerina.io/downloads/), the programming language used to define the external authentication service. + +## Structure of the Sample + +``` +external-authentication-service + ├── service.bal + |── types.bal + ├── legacy-idp-utils.bal + ├── asgardeo-utils.bal + ├── Ballerina.toml + └── README.md +``` + +- `service.bal` contains the implementation of the external authentication service. This file acts as the main entry point to the service and defines the three REST APIs. +- `types.bal` contains the type definitions used in the service. +- `legacy-idp-utils.bal` contains the utility functions to authenticate users against the legacy system. +- `asgardeo-utils.bal` contains the utility functions to validate users against Asgardeo. + +## Setting up the Sample + +1. Create a new Ballerina package. Learn how to do so in the [Ballerina documentation](https://ballerina.io/learn/get-started/). +2. Copy the content of the `service.bal`, `types.bal`, `legacy-idp-utils.bal`, and `asgardeo-utils.bal` files to the respective files in your Ballerina package. +3. Implement the logic as per your requirement. +4. Build the Ballerina package using the following command: + ```bash + bal build + ``` +5. Run the Ballerina package using the following command: + ```bash + bal run + ``` + +Follow the Asgardeo documentation to configure the external authentication service with Asgardeo and Choreo. diff --git a/user-migration-samples/asgardeo/external-authentication-service/asgardeo-utils.bal b/user-migration-samples/asgardeo/external-authentication-service/asgardeo-utils.bal new file mode 100644 index 000000000..86b498762 --- /dev/null +++ b/user-migration-samples/asgardeo/external-authentication-service/asgardeo-utils.bal @@ -0,0 +1,67 @@ +// Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). All Rights Reserved. +// +// WSO2 LLC. licenses this file to you 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. + +import ballerina/http; +import ballerina/log; +import ballerina/regex; + +// Configurable parameters. +configurable string asgardeoUrl = ?; +configurable AsgardeoAppConfig asgardeoAppConfig = ?; + +// Asgardeo scopes to invoke the APIs. +final string asgardeoScopes = "internal_user_mgt_view"; + +final http:Client asgardeoClient = check new (asgardeoUrl, { + auth: { + ...asgardeoAppConfig, + scopes: asgardeoScopes + } +}); + +# Retrieve the given user from Asgardeo. +# +# + id - The id of the user. +# + return - The AsgardeoUser if the user is found, else an error. +isolated function getAsgardeoUser(string id) returns AsgardeoUser|error { + + // Retrieve user from the Asgardeo server given the user id. + json|error jsonResponse = asgardeoClient->get("/scim2/Users/" + id); + + // Handle error response. + if jsonResponse is error { + log:printError(string `Error while fetching Asgardeo user for the id: ${id}.`, jsonResponse); + return error("Error while fetching the user."); + } + + AsgardeoUserResponse response = check jsonResponse.cloneWithType(AsgardeoUserResponse); + + if response.userName == "" { + log:printError(string `A user not found for the id: ${id}.`); + return error("User not found."); + } + + // Extract the username from the response. + string username = regex:split(response.userName, "/")[1]; + + log:printInfo("Successfully retrieved the username from Asgardeo."); + + // Return the user object. + return { + id: response.id, + username: username + }; +} diff --git a/user-migration-samples/asgardeo/external-authentication-service/legacy-idp-utils.bal b/user-migration-samples/asgardeo/external-authentication-service/legacy-idp-utils.bal new file mode 100644 index 000000000..672911e7b --- /dev/null +++ b/user-migration-samples/asgardeo/external-authentication-service/legacy-idp-utils.bal @@ -0,0 +1,53 @@ +// Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). All Rights Reserved. +// +// WSO2 LLC. licenses this file to you 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. + +import ballerina/http; +import ballerina/log; + +// Configurable parameters. +configurable string legacyIDPUrl = ?; + +# Method to authenticate the user. +# +# + user - The user object. +# + return - An error if the authentication fails. +isolated function authenticateUser(User user) returns error? { + + // Create a new HTTP client to connect to the external IDP. + final http:Client legacyIDPClient = check new (legacyIDPUrl, { + auth: { + username: user.username, + password: user.password + }, + secureSocket: { + enable: false + } + }); + + // Authenticate the user by invoking the external IDP. + // In this example, the external authentication is done invoking the SCIM2 Me endpoint. + // You may replace this with an implementation that suits your IDP. + http:Response response = check legacyIDPClient->get("/scim2/Me"); + + // Check if the authentication was unsuccessful. + if response.statusCode == http:STATUS_UNAUTHORIZED { + log:printError(string `Authentication failed for the user: ${user.id}. Invalid credentials`); + return error("Invalid credentials"); + } else if response.statusCode != http:STATUS_OK { + log:printError(string `Authentication failed for the user: ${user.id}.`); + return error("Authentication failed"); + } +} diff --git a/user-migration-samples/asgardeo/external-authentication-service/resources/images/external_authentication-choreo-service.png b/user-migration-samples/asgardeo/external-authentication-service/resources/images/external_authentication-choreo-service.png new file mode 100644 index 000000000..9b73af118 Binary files /dev/null and b/user-migration-samples/asgardeo/external-authentication-service/resources/images/external_authentication-choreo-service.png differ diff --git a/user-migration-samples/asgardeo/external-authentication-service/service.bal b/user-migration-samples/asgardeo/external-authentication-service/service.bal new file mode 100644 index 000000000..6adf9912f --- /dev/null +++ b/user-migration-samples/asgardeo/external-authentication-service/service.bal @@ -0,0 +1,205 @@ +// Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). All Rights Reserved. +// +// WSO2 LLC. licenses this file to you 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. + +import ballerina/http; +import ballerina/log; +import ballerina/uuid; + +// In this example, authentication results are stored in an in-memory map and hence supports only +// single-replica deployments. This is not recommended for production use. You need to replace this +// with a high available implementation that suits your requirement (i.e. DB or cache service). +isolated map userAuthContextMap = {}; + +isolated function pushToContext(string contextId, AuthenticationContext context) { + + lock { + userAuthContextMap[contextId] = context; + } +} + +isolated function isContextExists(string contextId) returns boolean { + + lock { + return userAuthContextMap.hasKey(contextId); + } +} + +isolated function popFromContext(string contextId) returns AuthenticationContext { + + lock { + return userAuthContextMap.remove(contextId); + } +} + +// Authentication service implementation. +service / on new http:Listener(9090) { + + resource function post start\-authentication(http:Caller caller, User user) { + + string contextId = uuid:createType1AsString(); + + log:printInfo(string `${contextId}: Received authentication request for the user: ${user.id}.`); + + do { + // Create future to authenticate user with the external IDP. + future authStatusFuture = start authenticateUser(user.cloneReadOnly()); + + // Return request received response to Asgardeo. + check caller->respond({ + body: { + message: "Received", + contextId: contextId + } + }); + + // Retrieve user from Asgardeo for the given user id. + // In this example, username is validated back with Asgardeo to ensure it is a valid user. + // You may replace this with your own logic. + future asgardeoUserFuture = start getAsgardeoUser(user.id); + + // Wait for the response from external legacy IDP. If no error, it is assumed as + // a successful authentication. + error? authStatus = check wait authStatusFuture; + + log:printInfo(string `${contextId}: User authenticated successfully with external IDP.`); + + // Wait for the response of Asgardeo invocation. + AsgardeoUser|error asgardeoUser = check wait asgardeoUserFuture; + log:printInfo(string `${contextId}: User retrieved from Asgardeo.`); + + if asgardeoUser is error { + log:printInfo(string `${contextId}: Error occurred while retrieving user from Asgardeo.`, + asgardeoUser); + fail error("Something went wrong."); + } + + // Validate the username. + if asgardeoUser.username !== user.username { + log:printInfo(string `${contextId}: Invalid username provided for the user: ${user.id}.`); + fail error("Invalid credentials"); + } + log:printInfo(string `${contextId}: Username validated successfully.`); + + log:printInfo(string `${contextId}: External authentication successful for the user: ${user.id}.`); + + // Add successful authentication result to the map. + AuthenticationContext context = { + username: user.username, + status: "SUCCESS", + message: "Authenticated successful" + }; + pushToContext(contextId, context); + + } on fail error err { + if err.message() == "Invalid credentials" { + log:printInfo(string `${contextId}: Invalid credentials provided for the user: ${user.id}.`); + + AuthenticationContext context = { + username: user.username, + status: "FAIL", + message: "Invalid credentials" + }; + pushToContext(contextId, context); + } else { + log:printError(string `${contextId}: Error occurred while authenticating the user: ${user.id}.`, err); + + AuthenticationContext context = { + username: user.username, + status: "FAIL", + message: "Something went wrong" + }; + pushToContext(contextId, context); + } + } + } + + resource function post authentication\-status(AuthenticationStatusRequest authStatus) + returns http:Ok|http:BadRequest { + + string contextId = authStatus.contextId; + string username = authStatus.username; + + log:printInfo(string `Received authentication status check for the context id: ${contextId}.`); + + if (isContextExists(contextId)) { + AuthenticationContext? context = popFromContext(contextId); + + if (context == null) { + log:printInfo( + string `${contextId}: Error while retrieving the authentication status. Context not found.`); + + return { + body: { + message: "Invalid context id" + } + }; + } + + log:printInfo(string `${contextId}: Authentication status retrieved successfully.`); + + if (context.username == username) { + log:printInfo(string `${contextId}: Username validated successfully.`); + + return { + body: { + status: context.status, + message: context.message + } + }; + } else { + log:printInfo(string `${contextId}: Provided username does NOT match with the context username.`); + + return { + body: { + status: "FAIL", + message: "Invalid request" + } + }; + } + } else { + log:printInfo(string `Authentication status not found for the context id: ${contextId}.`); + + return { + body: { + message: "Invalid context id" + } + }; + } + } + + resource function get authentication\-status(string contextId) returns http:Ok { + + log:printInfo(string `Received status polling query for the context id: ${contextId}.`); + + if (isContextExists(contextId)) { + log:printInfo(string `${contextId}: Context found for the status query.`); + + return { + body: { + status: "COMPLETE" + } + }; + } else { + log:printInfo(string `${contextId}: Context not found for the status query.`); + + return { + body: { + status: "PENDING" + } + }; + } + } +} diff --git a/user-migration-samples/asgardeo/external-authentication-service/types.bal b/user-migration-samples/asgardeo/external-authentication-service/types.bal new file mode 100644 index 000000000..94c38494a --- /dev/null +++ b/user-migration-samples/asgardeo/external-authentication-service/types.bal @@ -0,0 +1,50 @@ +// Copyright (c) 2024, WSO2 LLC. (https://www.wso2.com). All Rights Reserved. +// +// WSO2 LLC. licenses this file to you 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. + +type User record {| + readonly string id; + readonly string username; + readonly string password; +|}; + +type AsgardeoUser record {| + string id; + string username; +|}; + +type AsgardeoAppConfig readonly & record {| + string tokenUrl; + string clientId; + string clientSecret; +|}; + +type AsgardeoUserResponse record {| + string id; + string userName; + string[] emails; + json...; +|}; + +type AuthenticationContext record {| + readonly string username; + readonly string status; + readonly string message?; +|}; + +type AuthenticationStatusRequest record {| + readonly string contextId; + readonly string username; +|};