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

Added TD Ameritrade provider #3238

Closed
Closed
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
19 changes: 19 additions & 0 deletions src/providers/td-ameritrade.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export default function TDAmeritrade(options) {
return {
id: "td",
name: "TD Ameritrade",
type: "oauth",
version: "2.0",
params: { grant_type: "authorization_code" },
accessTokenUrl: "https://api.tdameritrade.com/v1/oauth2/token",
requestTokenUrl: "https://api.tdameritrade.com/v1/oauth2/token",
authorizationUrl: `https://auth.tdameritrade.com/auth?response_type=code`,
profileUrl: `https://api.tdameritrade.com/v1/accounts`,
profile(accounts) {
return {
id: accounts[0].securitiesAccount.accountId,
}
},
...options,
}
}
5 changes: 5 additions & 0 deletions src/server/lib/oauth/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,11 @@ async function getOAuth2AccessToken (code, provider, codeVerifier) {
if (provider.id === 'reddit') {
headers.Authorization = 'Basic ' + Buffer.from((provider.clientId + ':' + provider.clientSecret)).toString('base64')
}
// Added as a fix for TD Ameritrade Authentication
if (provider.id === 'td') {
params.access_type = 'offline'
params.code = decodeURIComponent(params.code)
}

if (provider.id === 'identity-server4' && !headers.Authorization) {
headers.Authorization = `Bearer ${code}`
Expand Down
1 change: 1 addition & 0 deletions types/providers.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ export type OAuthProviderType =
| "Slack"
| "Spotify"
| "Strava"
| "TDAmeritrade"
| "Twitch"
| "Twitter"
| "VK"
Expand Down
109 changes: 109 additions & 0 deletions www/docs/providers/td-ameritrade.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
---
id: td
title: TD Ameritrade
---

## Documentation

https://developer.tdameritrade.com/content/authentication-faq

## Example

```js
import NextAuth from "next-auth"
import Providers from "next-auth/providers"

export default NextAuth({
providers: [
Providers.TDAmeritrade({
clientId: process.env.TD_CLIENT_ID,
}),
],
// Everything below this point is for refresh token rotation in case you
// want to use access tokens to query the TD Ameritrade API
callbacks: {
async jwt(token, _, account) {
// Initial sign in
if (account) {
return {
accessToken: account.access_token,
accessTokenExpires: Date.now() + account.expires_in * 1000,
refreshToken: account.refresh_token
}
}

// Return previous token if the access token has not expired yet
if (Date.now() < token.accessTokenExpires) {
return token
}

// Access token has expired, try to update it
return refreshAccessToken(token)
},
async session(session, token) {
session.accessToken = token.accessToken
return session
},
},
})

...

/**
* Takes a token, and returns a new token with updated
* `accessToken` and `accessTokenExpires`. If an error occurs,
* returns the old token and an error property
*/
async function refreshAccessToken(token) {
try {
const url =
"https://api.tdameritrade.com/v1/oauth2/token?" +
new URLSearchParams({
client_id: process.env.TD_CLIENT_ID,
grant_type: "refresh_token",
refresh_token: token.refreshToken,
})

const response = await fetch(url, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
method: "POST",
})

const refreshedTokens = await response.json()

if (!response.ok) {
throw refreshedTokens
}

return {
...token,
accessToken: refreshedTokens.access_token,
accessTokenExpires: Date.now() + refreshedTokens.expires_in * 1000,
refreshToken: refreshedTokens.refresh_token ?? token.refreshToken, // Fall back to old refresh token
}
} catch (error) {
console.log(error)
return {
...token,
error: "RefreshAccessTokenError",
}
}
}

...

```

## Instructions

### Configuration

:::tip
An app must be created at https://developer.tdameritrade.com/user/me/apps
:::

- Set the 'Callback URL' to: http://localhost:3000/api/auth/callback/td

- Add an environment variable TD_CLIENT_ID that matches the pattern: `${TD_CONSUMER_KEY}@AMER.OAUTHAP` where `TD_CONSUMER_KEY` is the Consumer Key of the app you created.