Skip to content

Commit

Permalink
Merge pull request #1 from manuelseeger/move-to-ts
Browse files Browse the repository at this point in the history
Move to TS
  • Loading branch information
manuelseeger authored Apr 28, 2024
2 parents a12cd26 + 9526e48 commit 149c0cc
Show file tree
Hide file tree
Showing 18 changed files with 7,464 additions and 378 deletions.
14 changes: 14 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
max_line_length = 80
trim_trailing_whitespace = true

[*.md]
max_line_length = 0
trim_trailing_whitespace = false
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ node_modules/
.vscode/
*.pfx
*.pem
*.cer
_debugassertion.xml
_exampleassertion.xml
verify/bin/
verify/obj/
dist/
lib/
integrationtest/
coverage/
Empty file added .npmignore
Empty file.
9 changes: 9 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"trailingComma": "all",
"tabWidth": 4,
"semi": true,
"singleQuote": true,
"printWidth": 80,
"bracketSameLine": false,
"arrowParens": "always"
}
106 changes: 60 additions & 46 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,77 +1,91 @@
# OAuth SAML Bearer Client

This is a basic implementation of an OauthSAMLBearer client as used by SAP Cloud 4 Customer (C4C).
This is a basic implementation of an OauthSAMLBearer client as used by SAP Cloud 4 Customer (C4C) and other SAP applications.

The OAuthSAMLBearer flow allows a client application to make requests to the SAP OData API within the context of a regular user. No elevated permissions are required by the client application, and the OData API will respect access rights of the user in whose name the request is being made.
The OAuthSAMLBearer flow allows a client application to make requests to the SAP OData API within the context of a regular user. No elevated permissions are required by the client application, and the OData API will respect access rights of the user in whose name the request is being made.

## How to use
## Usage

Setup an OAuth identity provider in C4C. Prepare the key and certificate of the identity provider in PEM format.
Setup an OAuth identity provider in the target application. Generate an SSL keypair for the identity provider and store the key and certificate of the identity provider in PEM format (see [generate.sh](test/fixture/generate.sh)).

Prepare a config object with the following properties:

| Property | Description |
|---|---|
| assertionTemplate | Path to an XML template file for the assertion. See [assets/assertion_template_minimal.xml](assets/assertion_template_minimal.xml) |
| clientId | ClientID of the OAuth token endpoint credentials |
| clientSecret | Secret of the OAuth token endpoint credentials |
| tokenEndPoint | URL of the OAuth token endpoint |
| entityId | SSO base URL of the C4C tenant |
| issuer | Name of the OAuth 2.0 identity provider configured in C4C |
| nameIdFormat | Format of the user ID, either emailAdress or unspecified |
| certificate | Certificate assigned to the OAuth identity provider in C4C (PEM string) |
| signingKey | Private key of the OAuth identity provider used for signing (PEM string) |
| Property | Description |
| ------------- | ------------------------------------------------------------------------------------ |
| clientId | ClientID of the OAuth token endpoint credentials |
| clientSecret | Secret of the OAuth token endpoint credentials |
| tokenEndPoint | URL of the OAuth token endpoint |
| entityId | SSO base URL of the target application tenant |
| issuer | Name of the OAuth 2.0 identity provider configured in target application |
| nameIdFormat | Format of the user ID, either emailAdress or unspecified |
| certificate | Certificate assigned to the OAuth identity provider in C4C (PEM string) |
| signingKey | Private key of the OAuth identity provider used for signing (unencrypted PEM string) |

```js
const config = {
assertionTemplate: 'assets/assertion_template_minimal.xml',
clientId: '_1234567OGA',
clientSecret: 'k4xv77E3qRIaLeDKnVQG',
tokenEndPoint: 'https://my123456.crm.ondemand.com/sap/bc/sec/oauth2/token',
entityId: 'https://my123456-sso.crm.ondemand.com',
import { OAuthSAMLBearerClient } from 'oauth-saml-bearer-client';
import fs from 'fs';

const certificate = fs.readFileSync('certificate.pem', 'utf8');
const private_key = fs.readFileSync('private_key.pem', 'utf8');

const client = new OAuthSAMLBearerClient({
clientId: '_123456789',
clientSecret: 'ABC123456789',
entityId: 'HTTPS://my123456-sso.crm.ondemand.com',
tokenEndPoint: 'https://my123456.crm.ondemand.com/sap/bc/sec/oauth2/token',
issuer: 'MY-IDP',
certificate: certificate,
signingKey: private_key,
nameIdFormat: 'emailAddress',
certificate: await fs.readFile('cert.pem', { encoding: 'utf8' }),
signingKey: await fs.readFile('key.pem', { encoding: 'utf8' })
}
scope: 'UIWC:CC_HOME',
});

const oauthClient = new OAuthSAMLBearerClient(config)
const user = '[email protected]';

const nameId = '[email protected]'
const token = await client.getAccessToken(user);

let tokenResponse = await oauthClient.requestToken(nameId)
console.log(token);
```
If successful, the response is an [axios response object](https://axios-http.com/docs/res_schema) with a JSON payload containing token and validity.

If successful, the response is an access token with scope and validity.

```json
{
"access_token": "ABY-0tpvHtyn8V_Y0kZFExeEUsu41FIi9fP45VdLXfd2Mlf_",
"token_type": "Bearer",
"expires_in": "3600",
{
"access_token": "ABY-0tpvHtyn8V_Y0kZFExeEUsu41FIi9fP45VdLXfd2Mlf_",
"token_type": "Bearer",
"expires_in": "3600",
"scope": "UIWC:CC_HOME"
}
```
See also [examples/usage.js](examples/usage-axios.js)

Method requestToken will always query the token endpoint for a new token. If you use method getAccessToken, the client will cache the last valid token and only request a new one once validity expires.
### Optional settings

| Property | Description |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| assertionTemplate | Custom template to build the assertion from. If not provided, [assets/assertion_template_minimal.xml](assets/assertion_template_minimal.xml) is used. |
| cacheTokens | Optional boolean to indicate whether requested tokens should be cached in memory until they expire (default=false). If not set or false, client will always request a new token. |

This can be used to transparently request the token on requests to the OData API, for example with axios:

This can be used to transparently request the token on requests to the OData API, for example with axios:
```js
axios.interceptors.request.use(async axiosConfig => {
const token = await oauthClient.getAccessToken(nameId)
axiosConfig.headers.Authorization = `Bearer ${token}`
return axiosConfig
})
axios.interceptors.request.use(async (axiosConfig) => {
const token = await oauthClient.getAccessToken(nameId);
axiosConfig.headers.Authorization = `Bearer ${token}`;
return axiosConfig;
});
```
See also [examples/usage-axios.js](examples/usage-axios.js)

## A word of caution
The C4C token endpoint API is extremely sensitive. The API will return 400 and a generic exception if there is the slightest deviation from the expected assertion format. The exception doesn't give any indication whether the error is in XML syntax, the signature, the expected values within the assertion, or anything else. All one can do is trial and error until it works.
## Caution with server implementations (C4C)

The C4C token endpoint API is extremely sensitive. The API will return 400 and a generic exception if there is the slightest deviation from the expected assertion format. The exception doesn't give any indication whether the error is in XML syntax, the signature, the expected values within the assertion, or anything else. All one can do is trial and error until it works.

## Documentation
Documentation of the OAuth SAML Bearer flow is unfortunately rare. Here is a basic overview from SAP:

Documentation of the OAuth SAML Bearer flow is unfortunately rare. Here is a basic overview from SAP:
https://wiki.scn.sap.com/wiki/display/Security/Using+OAuth+2.0+from+a+Web+Application+with+SAML+Bearer+Assertion+Flow

To set up a trusted third party who is allowed to authenticate users using the OAuthSAMLBearer flow, follow these instructions:
To set up a trusted third party who is allowed to authenticate users using the OAuthSAMLBearer flow, follow these instructions:
https://help.sap.com/products/BTP/65de2977205c403bbc107264b8eccf4b/40d20a26f3dd445facff151b249fcf94.html

The OAuth SAML Bearer specification proposal:
The OAuth SAML Bearer specification proposal:
https://tools.ietf.org/id/draft-ietf-oauth-saml2-bearer-10.html
58 changes: 0 additions & 58 deletions examples/usage-axios.js

This file was deleted.

35 changes: 0 additions & 35 deletions examples/usage.js

This file was deleted.

14 changes: 14 additions & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { Config } from '@jest/types';

const config: Config.InitialOptions = {
preset: 'ts-jest',
testEnvironment: 'node',
testPathIgnorePatterns: ['/node_modules/'], //, "int-test"],
coverageDirectory: 'coverage',
collectCoverageFrom: ['src/**/*.ts'],
transform: {
'^.+\\.tsx?$': ['ts-jest', { tsconfig: 'tsconfig.test.json' }],
},
};

export default config;
Loading

0 comments on commit 149c0cc

Please sign in to comment.