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 Backend Auth Handler Implementation #7

Merged
merged 9 commits into from
Dec 5, 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
10 changes: 10 additions & 0 deletions distribution/apim-accelerator/bin/merge.sh
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,16 @@ if [ "${smart_on_fhir_enabled}" == "true" ]; then
echo -e "\n#[healthcare.identity.claims]\n#patient_id_claim_uri = \"http://wso2.org/claims/patientId\"\n#patient_id_key = \"patientId\"\n#fhirUser_resource_url_context = \"/r4/Patient\"\n#fhirUser_resource_id_claim_uri = \"http://wso2.org/claims/patientId\"" | tee -a "${WSO2_OH_APIM_HOME}"/repository/conf/deployment.toml >/dev/null
fi

if grep -Fxq "#[[healthcare.backend.auth]]" "${WSO2_OH_APIM_HOME}"/repository/conf/deployment.toml || grep -Fxq "[[healthcare.backend.auth]]" "${WSO2_OH_APIM_HOME}"/repository/conf/deployment.toml
then
# code if found
echo -e "[WARN] healthcare.backend.auth configuration already exist"
else
# code if not found
echo -e "\n#[[healthcare.backend.auth]]\n## Name of the authentication method. This name must be matched with the Config Name policy attribute in the -\n## - Replace Backend Auth Token policy.\n#name = \"epic_pkjwt\"\n## Authentication type. Only pkjwt and client_credentials are supported atm.\n#auth_type = \"pkjwt\"\n## External Auth server's Token endpoint URL.\n#token_endpoint = \"https://localhost:9443/oauth2/token\"\n#client_id = \"client_id\"\n#private_key_alias = \"key_alias\"
\n#[[healthcare.backend.auth]]\n#name = \"epic_client_credentials\"\n#auth_type = \"client_credentials\"\n#token_endpoint = \"https://localhost:9443/oauth2/token\"\n#client_id = \"client_id\"\n#client_secret = \"client_secret\"" | tee -a "${WSO2_OH_APIM_HOME}"/repository/conf/deployment.toml >/dev/null
fi

if grep -Fxq "#[healthcare.identity.claim.mgt]" "${WSO2_OH_APIM_HOME}"/repository/conf/deployment.toml || grep -Fxq "[healthcare.identity.claim.mgt]" "${WSO2_OH_APIM_HOME}"/repository/conf/deployment.toml
then
# code if found
Expand Down
12 changes: 12 additions & 0 deletions distribution/apim-accelerator/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,10 @@
<fileset dir="${basedir}/../../product-accelerators/apim/components/org.wso2.healthcare.apim.gateway.security.jwt.generator/target">
<include name="org.wso2.healthcare.apim.gateway.security.jwt.generator-${project.version}.jar"/>
</fileset>
<!--PKJWT Backend Auth Handler-->
<fileset dir="${basedir}/../../product-accelerators/apim/components/org.wso2.healthcare.apim.backendauth/target">
<include name="org.wso2.healthcare.apim.backendauth-${project.version}.jar"/>
</fileset>
</copy>

<!--Add Bundles to lib-->
Expand Down Expand Up @@ -279,6 +283,14 @@
excludes="**/velocity_template.xml"/>
</copy>

<!--Add operation policies-->
<copy
todir="${product_home}/carbon-home/repository/resources/operation_policies">
<fileset
dir="${basedir}/../../distribution/apim-accelerator/resources/repository/resources/operation_policies"
includes="**"/>
</copy>

<!--Add bin folder with merge.sh-->
<copy
todir="${product_home}/bin">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -418,6 +418,24 @@ policy.limit.time_unit = "min"
patient_id_uri = "http://wso2.org/claims/patientId"
patient_id_key = "patientId"

#[[healthcare.backend.auth]]
# Name of the authentication method. This name must be matched with the Backend Auth Config policy attribute in the -
# - Replace Backend Auth Token policy.
#name = "epic_pkjwt"
## Authentication type. Only pkjwt and client_credentials are supported atm.
#auth_type = "pkjwt"
## External Auth server's Token endpoint URL.
#token_endpoint = "https://localhost:9443/oauth2/token"
#client_id = "client_id"
#private_key_alias = "key_alias"

#[[healthcare.backend.auth]]
#name = "epic_client_credentials"
#auth_type = "client_credentials"
#token_endpoint = "https://localhost:9443/oauth2/token"
#client_id = "client_id"
#client_secret = "client_secret"

#[healthcare.deployment.webapps]
#name = "Open Healthcare"
#name_container_css = ""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<class name="org.wso2.healthcare.apim.backendauth.BackendAuthenticator">
<property name="configName" value="{{backendAuthConfig}}"/>
</class>
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"category": "Mediation",
"name": "replaceBackendAuthToken",
"version": "v1",
"displayName": "Replace Backend Auth Token",
"description": "This handler will replace backend Auth token with a token from external Auth server",
"applicableFlows": [
"request"
],
"supportedGateways": [
"Synapse"
],
"supportedApiTypes": [
"HTTP"
],
"policyAttributes": [
{
"name": "backendAuthConfig",
"displayName": "Backend Auth Config",
"description": "Name of the backend auth server config. This has to an exact match with the config name in the deployment.toml [[healthcare.backend.auth]] section",
"type": "String",
"required": true
}
]
}
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,12 @@
<version>${carbon.kernel.version}</version>
<scope>test</scope>
</dependency>

<!-- Backend Authenticator related -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</dependency>
</dependencies>
</dependencyManagement>

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2024, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.wso2.healthcare</groupId>
<artifactId>product-accelerators</artifactId>
<version>1.0.0</version>
<relativePath>../../../pom.xml</relativePath>
</parent>

<artifactId>org.wso2.healthcare.apim.backendauth</artifactId>
<version>1.0.0</version>
<packaging>bundle</packaging>

<dependencies>
<dependency>
<groupId>org.apache.ws.commons.axiom</groupId>
<artifactId>axiom-api</artifactId>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.3.3</version>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

versions should be handled at the root pom

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

there was a build error in the tests of org.wso2.healthcare.apim.clientauth.jwt module once we specify the version of commons-logging in the root level.
Hence used the latest version

</dependency>
<dependency>
<groupId>org.apache.synapse</groupId>
<artifactId>synapse-core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.healthcare</groupId>
<artifactId>org.wso2.healthcare.apim.core</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project.artifactId}.${project.version}</Bundle-SymbolicName>
<Bundle-Name>${project.artifactId}</Bundle-Name>
<Export-Package>
org.wso2.healthcare.apim.backendauth.*;
</Export-Package>
<Import-Package></Import-Package>
<DynamicImport-Package>*</DynamicImport-Package>
<Fragment-Host>synapse-core</Fragment-Host>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Backend Authentication for WSO2 API Manager

This module provides a streamlined solution for integrating an external authentication server to securely obtain and
manage access tokens for backend service requests. By default, WSO2 API Manager's gateway forward the end-user's access token
from the invoking client to the backend API.
<br>This module replaces that default behavior by fetching a new access token
from an external OAuth 2.0-compliant authentication server and replacing the `Authorization` header with the
retrieved token.

## Configuration Model

```toml
[[healthcare.backend.auth]]
name = "backend-auth"
auth_type = "pkjwt" #"pkjwt" or "client-credentials"
token_endpoint = "https://localhost:9443/oauth2/token"
client_id = "client_id"
client_secret = "client_secret" # Only for Client Credentials flow
private_key_alias = "key_alias" # Only for PKJWT flow
```
### Parameters

| Parameter | Description | Example Value |
|---------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------|
| `name` | Name of the authentication method. This name must be matched with the `Backend Auth Config` policy attribute in the `Replace Backend Auth Token` policy. | `epic-pkjwt` |
| `auth_type` | Authentication type. Only `pkjwt` and `client_credentials` are supported atm. | `pkjwt` |
| `token_endpoint` | The URL of the external auth server's token endpoint for obtaining tokens. | `https://external.auth.com:9443/oauth2/token` |
| `client_id` | The client identifier registered with the auth server. | `client_id` |
| `client_secret` | The client secret associated with the client ID (if applicable). | `client_secret` |
| `private_key_alias` | The alias of the private key used for signing JWTs (if applicable). This key must be added to the Primary Keystore | `key_alias` |


## Key Features

- **External Auth Server Integration**: Connect to an external authentication server that supports OAuth 2.0 to
retrieve tokens for backend services.
- **Grant Type Support**: Supports the following OAuth 2.0 grant types:
- JWT Bearer Grant
- Client Credentials Grant
- **Dynamic Header Replacement**: Automatically replaces the existing `Authorization` header in API requests with the
access token retrieved from the configured auth server.

## Use of Private-Public key pair for PKJWT Auth flow
1. Generate an RSA key pair. Recommended signature algorithm is `RS256`.
2. Upload the private key to the WSO2 API Manager's Key Store. The alias of the uploaded key should be
provided in the configuration(`private_key_alias`).
3. Configure the public key in the external authentication server.
4. If you're enabling SSL, provide the public key of the external authentication server in the
WSO2 API Manager's truststore(`client-truststore.jks`).


## Important Notes
### Convert a Private Key from `.pem` to `PKCS#12` Format
```bash
openssl pkcs12 -export \
-in <cert_for_sign> \
-inkey <privatekey_in_pem_format> \
-out <out_file_name>.p12 \
-name <alias> \
-passout <password>
```

### Import a Private Key in `PKCS#12` format to a `JKS` Key Store
```bash
keytool -importkeystore \
-srckeystore <p12_file_path> \
-srcstoretype PKCS12 \
-destkeystore <jks_file_path> \
-deststoretype JKS \
-srcstorepass <p12_file_password> \
-deststorepass <jks_password> \
-srcalias <alias_used_in_p12> \
-destalias <alias_to_be_used_in_JKS>
```


Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org).
*
* 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.
*/

package org.wso2.healthcare.apim.backendauth;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.mediators.AbstractMediator;
import org.wso2.healthcare.apim.backendauth.impl.BackendAuthHandler;
import org.wso2.healthcare.apim.backendauth.impl.ClientCredentialsBackendAuthenticator;
import org.wso2.healthcare.apim.backendauth.impl.PrivateKeyJWTBackendAuthenticator;
import org.wso2.healthcare.apim.core.OpenHealthcareEnvironment;
import org.wso2.healthcare.apim.core.OpenHealthcareException;
import org.wso2.healthcare.apim.core.config.BackendAuthConfig;

import java.util.Map;

/**
* Backend authenticator mediator.
*/
public class BackendAuthenticator extends AbstractMediator {

private static final Log log = LogFactory.getLog(BackendAuthenticator.class);
private String configName;
private final Map<String, BackendAuthConfig> backendAuthConfig;
private final PrivateKeyJWTBackendAuthenticator privateKeyJWTBackendAuthenticator;
private final ClientCredentialsBackendAuthenticator clientCredentialsBackendAuthenticator;

public BackendAuthenticator() throws OpenHealthcareException {
backendAuthConfig = OpenHealthcareEnvironment.getInstance().getConfig().getBackendAuthConfig();
privateKeyJWTBackendAuthenticator = new PrivateKeyJWTBackendAuthenticator();
clientCredentialsBackendAuthenticator = new ClientCredentialsBackendAuthenticator();

}

@Override
public boolean mediate(MessageContext messageContext) {
if (log.isDebugEnabled()) {
log.debug("Backend authenticator mediator is invoked.");
}

BackendAuthConfig config = backendAuthConfig.get(configName);
String accessToken;
BackendAuthHandler currentAuthenticator;

if (configName == null) {
log.error("Auth type is not defined in the message context.");
return false;
}
switch (config.getAuthType()) {
case Constants.POLICY_ATTR_AUTH_TYPE_PKJWT:
if (log.isDebugEnabled()) {
log.debug("Auth type is PKJWT.");
}
currentAuthenticator = privateKeyJWTBackendAuthenticator;
accessToken = privateKeyJWTBackendAuthenticator.fetchValidAccessToken(messageContext, config);
break;
case Constants.POLICY_ATTR_AUTH_TYPE_CLIENT_CRED:
if (log.isDebugEnabled()) {
log.debug("Auth type is CLIENT CREDENTIALS.");
}
currentAuthenticator = clientCredentialsBackendAuthenticator;
accessToken = clientCredentialsBackendAuthenticator.fetchValidAccessToken(messageContext, config);
break;
default:
log.error("Auth type is not supported.");
return false;
}

if (messageContext instanceof Axis2MessageContext) {
org.apache.axis2.context.MessageContext axisMsgCtx =
((Axis2MessageContext) messageContext).getAxis2MessageContext();
Object headers = axisMsgCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
if (headers instanceof Map) {
Map headersMap = (Map) headers;
if (headersMap.get(Constants.HEADER_NAME_AUTHORIZATION) != null) {
headersMap.remove(Constants.HEADER_NAME_AUTHORIZATION);
}
headersMap.put(Constants.HEADER_NAME_AUTHORIZATION, currentAuthenticator.getAuthHeaderScheme() + accessToken);
axisMsgCtx.setProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS, headersMap);
} else {
log.warn("Transport headers are not available in the message context.");
}
} else {
log.error("Message context is not an instance of Axis2MessageContext.");
}
return true;
}

public String getConfigName() {
return configName;
}

@SuppressWarnings("Setter will be called by the ESB config builder")
public void setConfigName(String configName) {
this.configName = configName;
}
}
Loading
Loading