-
Notifications
You must be signed in to change notification settings - Fork 2
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
Changes from 8 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
d50ab23
initial commit
isuruh15 e018c15
add configs and installation steps
isuruh15 89d0fb3
address review comments
isuruh15 fc5b878
update readme
isuruh15 b8da50d
fix review comments
isuruh15 daa4bf5
add comments to configs
isuruh15 2baf7e5
address review comments
isuruh15 60cde3c
minor fixes
isuruh15 a78bbae
formatting fixes
isuruh15 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
3 changes: 3 additions & 0 deletions
3
...sources/repository/resources/operation_policies/definitions/replaceBackendAuthToken_v1.j2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
25 changes: 25 additions & 0 deletions
25
...es/repository/resources/operation_policies/specifications/replaceBackendAuthToken_v1.json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
85 changes: 85 additions & 0 deletions
85
product-accelerators/apim/components/org.wso2.healthcare.apim.backendauth/pom.xml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | ||
</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> |
76 changes: 76 additions & 0 deletions
76
...uct-accelerators/apim/components/org.wso2.healthcare.apim.backendauth/readme.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | ||
``` | ||
|
||
|
115 changes: 115 additions & 0 deletions
115
....backendauth/src/main/java/org/wso2/healthcare/apim/backendauth/BackendAuthenticator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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 ofcommons-logging
in the root level.Hence used the latest version