This repository has been archived by the owner on Apr 10, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 0f5127d
Showing
81 changed files
with
4,148 additions
and
0 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
# To get started with Dependabot version updates, you'll need to specify which | ||
# package ecosystems to update and where the package manifests are located. | ||
# Please see the documentation for all configuration options: | ||
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates | ||
|
||
version: 2 | ||
updates: | ||
- package-ecosystem: "gradle" | ||
directory: "/" | ||
schedule: | ||
interval: "weekly" | ||
day: "monday" |
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,36 @@ | ||
name: PR Validation | ||
|
||
on: | ||
pull_request: | ||
branches: | ||
- main | ||
|
||
jobs: | ||
build: | ||
runs-on: ubuntu-latest | ||
steps: | ||
- uses: actions/checkout@v2 | ||
- name: Set up JDK 11 | ||
uses: actions/setup-java@v2 | ||
with: | ||
java-version: '11' | ||
distribution: 'adopt' | ||
- name: Validate Gradle wrapper | ||
uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b | ||
- name: Cache Gradle packages | ||
uses: actions/cache@v2 | ||
with: | ||
path: | | ||
~/.gradle/caches | ||
~/.gradle/wrapper | ||
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} | ||
restore-keys: | | ||
${{ runner.os }}-gradle- | ||
- name: Build with Gradle | ||
run: ./gradlew build --info -Dorg.gradle.daemon=false | ||
- name: Cleanup Gradle Cache | ||
# Remove some files from the Gradle cache, so they aren't cached by GitHub Actions. | ||
# Restoring these files from a GitHub Actions cache might cause problems for future builds. | ||
run: | | ||
rm -f ~/.gradle/caches/modules-2/modules-2.lock | ||
rm -f ~/.gradle/caches/modules-2/gc.properties |
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,45 @@ | ||
name: Publish to Github Packages on Release | ||
on: | ||
release: | ||
branches: | ||
- main | ||
types: | ||
- created | ||
jobs: | ||
publish: | ||
runs-on: ubuntu-latest | ||
permissions: | ||
contents: read | ||
packages: write | ||
steps: | ||
- uses: actions/checkout@v2 | ||
- uses: actions/setup-java@v2 | ||
with: | ||
java-version: '11' | ||
distribution: 'adopt' | ||
- name: Validate Gradle wrapper | ||
uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b | ||
- name: Cache Gradle packages | ||
uses: actions/cache@v2 | ||
with: | ||
path: | | ||
~/.gradle/caches | ||
~/.gradle/wrapper | ||
key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }} | ||
restore-keys: | | ||
${{ runner.os }}-gradle- | ||
- name: Build with Gradle | ||
run: ./gradlew build --info -Dorg.gradle.daemon=false | ||
- name: Cleanup Gradle Cache | ||
# Remove some files from the Gradle cache, so they aren't cached by GitHub Actions. | ||
# Restoring these files from a GitHub Actions cache might cause problems for future builds. | ||
run: | | ||
rm -f ~/.gradle/caches/modules-2/modules-2.lock | ||
rm -f ~/.gradle/caches/modules-2/gc.properties | ||
- name: Publish package | ||
run: | | ||
NEW_VERSION=$(echo "${GITHUB_REF}" | cut -d "/" -f3) | ||
echo "Publishing new version: ${NEW_VERSION}" | ||
./gradlew -Pversion=${NEW_VERSION} publish | ||
env: | ||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} |
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,31 @@ | ||
*.class | ||
*.log | ||
# Mobile Tools for Java (J2ME) | ||
.mtj.tmp/ | ||
|
||
# Package Files # | ||
*.war | ||
*.ear | ||
#*.jar | ||
|
||
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml | ||
hs_err_pid* | ||
|
||
# output | ||
target/ | ||
build/ | ||
/bin/ | ||
out/ | ||
|
||
# eclipse | ||
.classpath | ||
.project | ||
.settings/ | ||
|
||
# idea | ||
*.iml | ||
*.ipr | ||
*.iws | ||
.idea | ||
.DS_Store | ||
.gradle/ |
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 @@ | ||
{ | ||
"settingsInheritedFrom": "whitesource-config/whitesource-config@main" | ||
} |
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,33 @@ | ||
# Contributor Covenant Code of Conduct | ||
|
||
# Our Pledge | ||
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. | ||
|
||
# Our Standards | ||
Examples of behavior that contributes to creating a positive environment include: | ||
Using welcoming and inclusive language | ||
Being respectful of differing viewpoints and experiences | ||
Gracefully accepting constructive criticism | ||
Focusing on what is best for the community | ||
Showing empathy towards other community members | ||
|
||
Examples of unacceptable behavior by participants include: | ||
The use of sexualized language or imagery and unwelcome sexual attention or advances | ||
Trolling, insulting/derogatory comments, and personal or political attacks | ||
Public or private harassment | ||
Publishing others' private information, such as a physical or electronic address, without explicit permission | ||
Other conduct which could reasonably be considered inappropriate in a professional setting | ||
|
||
# Our Responsibilities | ||
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. | ||
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. | ||
|
||
# Scope | ||
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. | ||
|
||
# Enforcement | ||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [email protected]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. | ||
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. | ||
|
||
# Attribution | ||
This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html |
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,15 @@ | ||
# Contributing to reuse | ||
|
||
### Issues | ||
|
||
Feel free to submit bugs or feature requests as issues. | ||
|
||
### Pull Requests | ||
|
||
These rules must be followed for any contributions to be merged into master. | ||
|
||
1. Fork this repo | ||
1. Make any desired changes | ||
1. Validate your changes meet your desired use case | ||
1. Ensure documentation has been updated | ||
1. Open a pull request |
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,20 @@ | ||
Copyright (c) 2021 Target Brands, Inc. | ||
|
||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
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,164 @@ | ||
# Token Manager for Salesforce | ||
|
||
This project makes Salesforce API calls with Spring a breeze. It exposes either a RestTemplate or WebClient that handles generating, refreshing and attaching an authorization token header for every API call. Just pass in your instance and user credentials via `application.yml`, autowire your desired bean and it takes care of the rest. | ||
|
||
## Usage | ||
|
||
To use this library, the following repository declaration and one of the dependencies to your project's `build.gradle` file. This will include the core module as well automatically. | ||
|
||
```groovy | ||
repositories { | ||
maven { | ||
name = "GitHubPackages" | ||
url = uri("https://maven.pkg.github.com/target/token-manager-for-salesforce") | ||
credentials { | ||
username = project.findProperty("gpr.user") ?: System.getenv("USERNAME") | ||
password = project.findProperty("gpr.token") ?: System.getenv("TOKEN") | ||
} | ||
} | ||
} | ||
dependencies { | ||
// for reactive applications | ||
implementation "com.tgt.crm:token-manager-for-salesforce-webflux:${libraryVersion}" | ||
// for non-reactive applications | ||
implementation "com.tgt.crm:token-manager-for-salesforce-webmvc:${libraryVersion}" | ||
} | ||
``` | ||
|
||
Find the latest version in the "packages" section of this repo. You will need access to the Github repository and will need to make your user and a personal access token available as a project or system property to authorize with Github and download the package. More details can be found [here](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-gradle-registry). | ||
|
||
Add the following to your `application.yml` file to pass in Salesforce properties from TAP secrets/environment variables. You can set explicit values for these properties instead of environment variables if you prefer. Ensure you don't check any secrets into Git. | ||
|
||
```yaml | ||
salesforce: | ||
host: ${SALESFORCE_HOST} | ||
username: ${SALESFORCE_USERNAME} | ||
password: ${SALESFORCE_PASSWORD} | ||
client-id: ${SALESFORCE_CLIENT_ID} | ||
client-secret: ${SALESFORCE_CLIENT_SECRET} | ||
auth-uri: /services/oauth2/token # optional | ||
retry-backoff-delay: 1000 # optional, configures retry for auth token requests only | ||
max-auth-token-retries: 3 # optional, configures retry for auth token requests only | ||
retry-backoff-multiplier: 2 # optional, configures retry for auth token requests only, only used by MVC, see SalesforceConfig for more info | ||
httpclient: | ||
max-conn-per-route: 20 # optional | ||
read-timeout: 30000 # optional, in milliseconds | ||
connection-timeout: 60000 # optional, in milliseconds | ||
mvc: # configs in this block only available for webmvc | ||
max-pools: 50 # optional | ||
connection-request-timeout: 30000 # optional, in milliseconds | ||
retries: 3 # optional, MVC only, configures default # of retries for all requests except auth token | ||
retry-interval: 2000 # optional, in milliseconds, configures default retry interval for all requests except auth token | ||
``` | ||
You should then be able to autowire the RestTemplate or WebClient bean in any component in your project and use it to make API calls to Salesforce. | ||
```java | ||
@Service | ||
public class SalesforceClient { | ||
|
||
private final RestTemplate salesforceRestTemplate; | ||
|
||
public SalesforceClient(@Qualifier("sfRestTemplate") final RestTemplate salesForceRestTemplate) { | ||
this.salesForceRestTemplate = salesForceRestTemplate; | ||
} | ||
|
||
public String querySalesforce() { | ||
ResponseEntity<String> sfResponse = | ||
salesForceRestTemplate.exchange( | ||
"/services/data/v50.0/query&q={query}", | ||
HttpMethod.GET, | ||
HttpEntity.EMPTY, | ||
String.class, | ||
"SELECT Id FROM Case"); | ||
|
||
return sfResponse.getBody(); | ||
} | ||
} | ||
``` | ||
|
||
```java | ||
@Service | ||
public class SalesforceClient { | ||
|
||
private final WebClient salesforceWebClient; | ||
|
||
public SalesforceClient(@Qualifier("sfWebClient") final WebClient salesforceWebClient) { | ||
this.salesforceWebClient = salesforceWebClient; | ||
} | ||
|
||
public Mono<String> querySalesforce() { | ||
return webClient | ||
.get() | ||
.uri("/services/data/v50.0/query&q={query}", "SELECT Id FROM Case") | ||
.retrieve() | ||
.toEntity(String.class) | ||
.map(HttpEntity::getBody); | ||
} | ||
} | ||
``` | ||
|
||
### Minimum Requirements | ||
|
||
In your project, the following minimum versions of Spring Boot are required to use this library: | ||
|
||
* token-manager-for-salesforce-webflux: Spring Boot > 2.2.6.RELEASE | ||
* Spring Boot > 2.4.0 is recommended to support Wiretap for WebClient debug logging | ||
* token-manager-for-salesforce-webmvc: Spring Boot > 2.2.0.RELEASE | ||
|
||
### Metrics | ||
|
||
The application also emits one micrometer metric. If a token refresh fails, a counter is incremented. The counter is called `exception_counter` and has one tag `exception_type` with value `token_refresh_exception`. This can be used to set up an alert in Grafana if a token refresh ever fails. | ||
|
||
### How does it work? | ||
|
||
This library follows the [OAuth 2.0 Username-Password Flow](https://help.salesforce.com/articleView?id=remoteaccess_oauth_username_password_flow.htm&type=5) and is intended to be used with first-party applications. | ||
|
||
When your application starts up it will not have a token. The first time it makes an API call, the library intercepts the request, makes the appropriate API call to `/services/oauth2/token` for your configured instance as documented [here](https://help.salesforce.com/articleView?id=remoteaccess_oauth_endpoints.htm&type=5). The generated token is attached to the request as an `Authorization` header and the request proceeds. It is also cached in memory. | ||
|
||
Subsequent requests use the cached token and do not try to request a new token unless a 401 response is received. When a 401 is received, it attempts to generate a new token and retries the request. We use this behavior because Salesforce auth tokens do not return an `expires_in` property and the length of time they are valid for can vary from instance to instance based on admin settings. | ||
|
||
### Debugging Requests | ||
|
||
It is possible and occasionally useful to log complete HTTP requests and responses including URLs, query params, headers and bodies. Be careful as this has the potential to expose sensitive data such as passwords, auth tokens or API keys. It is recommended to only use this when running the application locally. | ||
|
||
To enable request/response logging for either mvc or webflux library, add the following to your `application.yml`: | ||
|
||
```yaml | ||
logging: | ||
level: | ||
com.tgt.crm.token: TRACE | ||
org.springframework.web.client.RestTemplate: DEBUG # additional RestTemplate debug logs, only applies to MVC. WARNING: logs sensitive info | ||
org.apache.http: DEBUG # additional detailed logging for RestTemplate, only applies to MVC. WARNING: logs sensitive info | ||
reactor.netty: TRACE # additional detailed logging for WebClient, only applies to WebFlux | ||
``` | ||
Note that setting log level to `DEBUG` will enable all debug logging except request/response logging. This is by design to help prevent unintentional sensitive data exposure. | ||
|
||
## Local Development | ||
|
||
If you make changes to this library locally and want to test those changes with another application, you can use [Gradle Composite Builds](https://docs.gradle.org/current/userguide/composite_builds.html). Essentially you just tell your other application to point to this project on your local file system instead of downloading the dependency from a repository. | ||
|
||
In the `settings.gradle` file in the root of the other project (you may have to create the file if it doesn't exist in that project), add the following line: | ||
|
||
``` | ||
includeBuild '../token-manager-for-salesforce' | ||
``` | ||
|
||
Where `../token-manager-for-salesforce` is the relative path to this project on your local file system. Now when you build the other project, it should use your local copy of `token-manager-for-salesforce`. Be sure to remove this change before committing. | ||
|
||
## Publish a new version | ||
|
||
Make the desired changes locally. Open a PR against the master branch, get it reviewed and merge. Tag this commit with a tag following [semantic versioning](https://semver.org/). This will trigger a new deployment of the library to [Github Packages](https://github.com/orgs/target/packages?repo_name=token-manager-for-salesforce). | ||
|
||
## Troubleshooting | ||
|
||
Problem: When I try to start my application I am getting a `NoClassDefFoundError` or a `NoSuchMethodError`. | ||
|
||
Solution: Check the version of Spring Boot you are using in your app and that it meets the minimum requirement listed above in the README. | ||
|
||
## License | ||
|
||
token-manager-for-salesforce is licensed under the [MIT License](LICENSE.md) | ||
|
||
Salesforce is a trademark of Salesforce.com, inc., and is used here with permission. |
Oops, something went wrong.