Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Asgardeo password migration sample #475

Merged
merged 3 commits into from
Jun 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions user-migration-samples/README.md
Original file line number Diff line number Diff line change
@@ -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
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"image": "ballerina/ballerina-devcontainer:2201.8.6",
"extensions": ["WSO2.ballerina"],
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
target
generated
Config.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
org = "WSO2"
name = "external_authentication_service"
version = "0.1.0"
distribution = "2201.8.6"

[build-options]
observabilityIncluded = true
Original file line number Diff line number Diff line change
@@ -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 <package-name>
```

Follow the Asgardeo documentation to configure the external authentication service with Asgardeo and Choreo.
Original file line number Diff line number Diff line change
@@ -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
};
}
Original file line number Diff line number Diff line change
@@ -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");
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading