Schwab OAuth 2.0: Refresh an access token
See more Schwab Examples
Run Authorize a desktop application first. Use the same app credentials and saved grant. Schwab documents 30 minutes for the access token and seven days from creation for the refresh token. Schedule refreshes using the returned expires_in and the saved UTC acquisition time. After the refresh window expires, repeat browser sign-in and consent.
The example sends a form-encoded refresh grant with HTTP Basic client authentication. It saves the returned access token and lifetime, adopts a replacement refresh token when supplied, and retains the original grant time. Use the saved access token in the Authorization: Bearer header on Schwab API requests. Coordinate refreshes if multiple processes share the same record.
If you used the earlier file-based example, run desktop authorization once to populate the secret store. After updating your application to use that store, retire the old schwab-access-token.json file.
These examples use the current user’s Windows Credential Manager or Apple Keychain. On Linux or Android, configure a persistent Chilkat Secrets backend for both examples before running them. The local manager on those platforms uses process memory. Use the same secret name for the same app and Schwab authorization. Give each separate authorization its own name.
Schwab Trader API OAuth guide · Register a Schwab app
Chilkat Ruby Downloads
require 'chilkat'
success = false
# Assumes Chilkat is unlocked. See Global Unlock Sample.
success = false
vault = Chilkat::CkSecrets.new()
vault.put_Location("local_manager")
vault.put_AutoSplit(true)
entry = Chilkat::CkJsonObject.new()
entry.UpdateString("appName","SchwabTrader")
entry.UpdateString("service","OAuth2")
entry.UpdateString("username","personal-desktop")
tokens = Chilkat::CkJsonObject.new()
success = vault.GetSecretJson(entry,tokens)
if (success != true)
print "Could not read the token record. Check the store and complete desktop authorization first." + "\n";
exit
end
if (tokens.HasMember("refresh_token") != true)
print "No saved refresh token. Complete desktop authorization." + "\n";
exit
end
refresh = tokens.stringOf("refresh_token")
if (refresh == "")
print "The saved refresh token is empty. Complete desktop authorization." + "\n";
exit
end
http = Chilkat::CkHttp.new()
http.put_RequireSslCertVerify(true)
http.put_BasicAuth(true)
http.put_Login("APP_KEY")
http.put_Password("APP_SECRET")
form = Chilkat::CkHttpRequest.new()
form.put_HttpVerb("POST")
form.put_ContentType("application/x-www-form-urlencoded")
form.AddParam("grant_type","refresh_token")
form.AddParam("refresh_token",refresh)
resp = Chilkat::CkHttpResponse.new()
success = http.HttpReq("https://api.schwabapi.com/v1/oauth/token",form,resp)
if (success != true)
if (resp.get_StatusCode() == 0)
print "No HTTP response. Check connectivity before retrying." + "\n";
exit
end
end
if (resp.get_StatusCode() != 200)
problem = Chilkat::CkJsonObject.new()
success = problem.Load(resp.bodyStr())
print "Schwab rejected the refresh. HTTP " + resp.get_StatusCode().to_s() + "\n";
if (success == true)
if (problem.StringOfEquals("error","invalid_grant",true) == true)
print "The grant is expired or invalid. Run desktop authorization again." + "\n";
end
if (problem.StringOfEquals("error","invalid_client",true) == true)
print "Check the app key and secret. If the seven-day grant has expired, authorize again." + "\n";
end
end
exit
end
reply = Chilkat::CkJsonObject.new()
success = reply.Load(resp.bodyStr())
if (success != true)
print "Unexpected token response." + "\n";
exit
end
if (reply.HasMember("access_token") != true)
print "The token response contained no access token." + "\n";
exit
end
access = reply.stringOf("access_token")
lifetime = reply.IntOf("expires_in")
if ((access == "") or (lifetime <= 0))
print "The token response lacks a usable access token or lifetime." + "\n";
exit
end
# A refresh response can omit the refresh token. Update it only when a new value is supplied.
if (reply.HasMember("refresh_token") == true)
replacement = reply.stringOf("refresh_token")
if (replacement != "")
tokens.UpdateString("refresh_token",replacement)
end
end
now = Chilkat::CkDateTime.new()
now.SetFromCurrentSystemTime()
tokens.UpdateString("obtained_at_utc",now.getAsTimestamp(false))
tokens.UpdateString("access_token",access)
tokens.UpdateInt("expires_in",lifetime)
success = vault.UpdateSecretJson(entry,tokens)
if (success != true)
print "Could not save the new credentials. Check the configured secret store." + "\n";
exit
end
print "Saved credentials. Access token lifetime in seconds: " + lifetime.to_s() + "\n";