Introduction
_____ _____ _ _
( _ )( _ ) ( )_ ( ) _
| ( ) || (_) | _ _ | ,_)| |__ (_) _
| | | || _ |( ) ( )| | | _ `\ | | /'_`\
| (_) || | | || (_) || |_ | | | | | |( (_) )
(_____)(_) (_)`\___/'`\__)(_) (_)()(_)`\___/
OAuth.io helps you to onboard your users with a suite of services easy to use.
Token API: Authorize your client apps on one of our 120+ OAuth provider.
Request API: Make authorized API calls to those OAuth providers in a simple way.
User Data API: Get the authenticated user's unified information.
User Management API: Signup/signin your user without any backend using multiple social identity.
Installation
Download the SDK
npm install oauthio
You can use CocoaPods to install OAuth.io in your iOS project
Download the android library:wget https://github.com/oauth-io/oauth-android/archive/master.zip
or clone it from github:git clone git@github.com:oauth-io/oauth-android
and import the oauthio folder into your project folder as a module. If you are not using Android Studio, you need to add this persmission into your `AndroidManifest.xml` file:<uses-permission android:name="android.permission.INTERNET" />
# add this line to your Podfile:
pod 'OAuth.io'
# run this command in your project directory
$ pod install
You can also install the framework manually. To do so, please follow the following steps: The framework is available in [https://github.com/oauth-io/oauth-ios](https://github.com/oauth-io/oauth-ios) as the Dist/OAuthiOS.framework file. To add it as a dependency in your projet in XCode, follow this procedure: - click on the project name in the Documents explorer go to Build phases - open the Link Binary with Libraries section - click on the + button - click on Add other... - Select the OAuthiOS.framework - Click on Add
You can use Composer to install the SDK in your PHP project.
# Add this line to require object of your composer.json file:
"oauth-io/oauth": "0.3.0"
# Run this command in your folder directory
$ composer update
#For Web app
bower install oauth.io
#Or for mobile app (using Phonegap)
phonegap plugin install https://github.com/oauth-io/oauth-phonegap
To ease your integration, SDKs are available in lots of language:
Install the SDK
var OAuth = require('oauthio');
// Initialize the SDK
OAuth.initialize('Your-public-key', 'Your-secret-key');
<script src="path/to/oauth.js"></script>
To install the SDK, you just need to load it in your source code.
// Initialize the SDK
OAuth.initialize('Your-public-key')
You need to create a class implementing the OAuthIODelegate. This delegate needs you to add the following methods: - "didReceiveOAuthIOResponse": called when a popup call is successful - "didFailWithOAuthIOError": called when a popup call is not successful - "didAuthenticateServerSide": when using the server-side mode, called on a successful authentication - "didFailAuthenticationServerSide": when using the server-side mode, called on an unsuccessful authentication
// Then in the class implementing OAuthIODelegate, you can initialize the SDK
// Initialize the SDK
_oauthioModal = [[OAuthIOModal alloc] initWithKey:@"Your-public-key" delegate:self];
use OAuth_io\OAuth;
$oauth = new OAuth();
// Initialize the SDK
$oauth->initialize('Your-public-key', 'Your-secret-key');
import io.oauth.OAuth;
...oauth = new OAuth(getActivity()); // Initialize the SDK oauth.initialize("Your-public-key");
When you create an OAuth.io application in your dashboard, a pair of public key, private key is generated. You will need this pair to initialize the SDK later on.
Token API - Client side
The Token API lets you authorize your app on behalf of your users on one of our 120+ API providers. The best known example is to add a Facebook connect to your website to ease the user's onboarding.
You can perform this authorization either client-side or server-side, depending your needs.
The Client side section is not available for this SDK
Configuration
To authorize your app using OAuth.io, you just need to add a provider to your OAuth.io app, copy/paste your provider's API Keys (usually client_id and client_secret), and specify a permission scope. Then, you can directly try a connection to the provider, by clicking on the Try auth
button.
Authorize with a popup
//Example with Facebook
OAuth.popup('facebook').done(function(facebook) {
//make API calls with `facebook`
}).fail(function(err) {
//todo when the OAuth flow failed
});
//Example with Twitter with the cache option enabled
OAuth.popup('twitter', {cache: true}).done(function(twitter) {
//make API calls with `twitter`
}).fail(function(err) {
//todo when the OAuth flow failed
})
In the OAuthIODelegate class, you can call the showWithProvider method, which shows a popup.
//Example with Twitter with no cache options
[_oauthioModal showWithProvider:@"twitter"];
//On success, the didReceiveOAuthIOResponde delegate method is called:
- (void)didReceiveOAuthIOResponse:(OAuthIORequest *)request
{
// Here you can use the request object to make requests directly
// or store it for later use (e.g. when a button is pressed)
_request_object = request;
}
oauth.popup("facebook", new OAuthCallback() {
@Override
public void onFinished(OAuthData data) {
if (data.status.equals("error"))
activity.displayError(data.error);
else {
// Do API calls with data
}
}
});
This mode asks the user's authorization in a simple popup. This gives you a request object, which allows you to perform API calls, or to retrieve the credentials (i.e. access or oauth tokens).
You can send multiple options to customize it.
Options | Description | Type | Default value |
---|---|---|---|
cache | If set to true, when the popup is called, the SDK will directly return the cached credentials (if available) through a "request object" instead of showing a popup everytime the user logs in. That is to say, once the user has seen the popup on his browser, his credentials are kept in the local storage. | boolean | false |
authorize | Some OAuth providers let developers send parameters to customize the authorization popup | Object | null |
Authorize with redirection
//Example with Google
OAuth.redirect('google', 'http://localhost/callback');
//in your callback page (can be the same page)
OAuth.callback('google').done(function(google) {
//make API calls with `google`
}).fail(function(err) {
//todo when the OAuth flow failed
})
Redirects to the provider's login page, where the user can accept your app's permissions. Once he/she accepts them, he/she is redirected to the callback URL.
Caching the request object
Client-side SDKs allow you to cache the credentials (i.e. access tokens) to not have to show the popup everytime you need the access token.
//Example with Twitter with the cache option enabled
OAuth.popup('twitter', {cache: true}).done(function(twitter) {
//make API calls with `twitter`
}).fail(function(err) {
//todo when the OAuth flow failed
})
//Example with Twitter with the cache option enabled
NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setObject:@"true" forKey:@"cache"];
[options setObject:@"true" forKey:@"clear-popup-cache"]; // prevents the webview from keeping cookies
[_oauthioModal showWithProvider:@"twitter" options:options];
Save your user's authorization in the cache
If the cache option is enabled, when the popup is called, it will directly create a request object from the cached credentials (if available) instead of showing a popup everytime the user logs in. That is to say, once the user has seen the popup once, his credentials are kept in the browser local storage for Javascript/Phonegap SDK and in the mobile with iOS and Android.
var twitter = OAuth.create('twitter');
//`twitter` is a request object.
//`twitter` can be `null` if the request object has not been created yet.
var twitter = OAuth.create('twitter');
//`twitter` is a request object.
//`twitter` can be `null` if the request object has not been created yet.
Creating a request object from Cache
Once credentials have been cached, you can re-create the request object from them (later or in another page for instance).
Note that you can also create a request object from existing credentials if needed.
Clearing the cache
//clear the cache for all providers
[oauthioModal clearCache];
//clear the cache for facebook
[oauthioModal clearCacheForProvider:@"facebook"];
//clears the cache for Facebook
OAuth.clearCache('facebook');
//removes cache for all providers
OAuth.clearCache();
You can of course partially or totally remove the cache generated by OAuth.io. Note that it can be used when you want to logout your users to be sure it will open the popup the next time they try to login.
Token API - Server side
The server side authorization is mostly used to get a refresh token and perform actions on behalf of your user when they are not online and connected on your website / app (for instance, crawl your user's feed and update it everyday even if the user is not connected).
Configuration
In the same way as for the client-side authorization, you need to add a provider to your OAuth.io app and copy paste your provider's API keys. But this time, you have to select a backend in your oauth.io app. This way, only server side authorization will be allowed.
You can also set the both mode to get a copy of the access_token client side too (and use all of the results method).
Simple server-side authorization
// Syntax
app.get(authorizeEndpoint, OAuth.auth(provider, urlToRedirect));
app.get(redirectEndpoint, OAuth.redirect(function(result, req, res) {
//todo with result
}));
// Example with Linkedin
app.get('/signin', OAuth.auth('linkedin', 'http://localhost:8080/oauth/redirect'));
app.get('/oauth/redirect', OAuth.redirect(function(result, req, res) {
if (result instanceof Error) {
res.send(500, "error: " + result.message);
}
result.me().done(function(me) {
console.log(me);
res.send(200, JSON.stringify(me));
});
}));
//Syntaxe
//in the Authorize endpoint
$oauth->redirect(provider, urlToRedirect);
//in the Redirect endpoint
$oauth->auth(provider, array('redirect' => true));
// Exemple with Google (using ZendFramwork, Controller /oauth)
// Action /signin (url: /oauth/authorize)
public function signinAction() {
try {
$this->oauth->redirect('google', '/oauth/redirect');
} catch (\Exception $e) {
echo $e->getMessage();
}
}
// Action /redirect (url: /oauth/redirect)
public function redirectAction() {
try {
$request_object = $this->oauth->auth('google', array(
'redirect' => true
));
} catch (\Exception $e) {
die($e->getMessage());
}
//Your user is authorized by Google
//You can use $request_object to make API calls on behalf of your user
}
<!-- In your html -->
<a href="/oauth/signin"></a>
This feature is not supported by this SDK
This method is the simplest way to achieve a server-side authorization.
You need to define 2 endpoints:
the first endpoint (
authorizeEndpoint
) is where you will redirect your users to authorize them to one of our 120+ OAuthprovider
then they will be redirected to the second endpoint (
redirectEndpoint
) with theresult
of the authorization in the callback.
In the HTML of your webapp, you just have to create a link to the first endpoint to start the authorization flow <a href="/url/to/authorizeEndpoint">Signin</a>
If an error occured, the error is placed in the result
.
Authorizing the user with both front-end and back-end SDKs
This method is a bit longer than the redirect one but can be used by any backend. This can be done in 3 steps:
//Node.js
var token = OAuth.generateStateToken(req);
res.send(200, {token:token});
// Example with Zend - /state action, called from the frontend
// to get a code
public function tokenAction() {
// This generates a token and stores it in the session
$token = $this->oauth->generateStateToken();
$array = array(
'token' => $token
);
$json = new JsonModel($array);
return $json;
}
- Generating a state token in your backend. Basically, it generates a unique id, stores it in session and sends it to the front.
//Javascript (client-side)
OAuth.popup(provider, {
state: params.token
}).done(function(result) {
$.post('/auth', {code: result.code})
})
- Authorizing your user with a client side SDK using the state token (you will receive a code instead of an access_token).
//Node.js
app.get('/auth', function(req, res) {
OAuth.auth(provider, req.session, {
code: JSON.parse(req.body).code
}).then(function(oauthResult) {
//todo with oauthResult
//oauthResult.access_token oauthResult.refresh_token
})
});
// PHP with Zend - endpoint on /auth
public function authAction() {
try {
$code = $this->getRequest()->getPost('code');
$request_object = $this->oauth->auth('facebook', array(
'code' => $code
));
$credentials = $request_object->getCredentials();
$json = new JsonModel(array('status' => 'success'));
if (!isset($credentials['access_token']) && !isset($credentials['oauth_token'])) {
$this->getResponse()->setStatusCode(400);
}
return $json;
} catch (\Exception $e) {
echo $e->getMessage();
}
}
POST https://oauth.io/auth/access_token Body: code=ePLi3...EQfdq key=public_key secret=secret_key
- Finally, from your backend, send the code to OAuth.io to get the access_token and refresh_token. OAuth.io will also send back the state token that you have to manually check. It must be the same state token as the one stored in session in the 1st step -- This is automatically done using a server-side SDK.
Request object from session
This feature is not supported by this SDK
OAuth.auth('facebook', req.session)
.then(function (request_object) {
// call endpoints with request_object here, or save it for later use
});
});
// Uses the $_SESSION array by default
$request_object = $this->oauth->auth('facebook');
// Note that you can specify another session array at initialization, for example:
$_SESSION['some_array'] = array();
$oauth->setSession($_SESSION['some_array']);
// Beware, the array is passed by reference, so you need to have a real grasp on the stored array
Once a user has been authorized by a provider, he is stored in session by the SDK. This means you can recreate the request object from the session. If the request object has an expires_in
field and the access token has expired, the SDK will automatically refresh the access_token
.
Building a request object from saved credentials
// Retrieve the credentials and save them
$credentials = $old_request_object->getCredentials();
// Later use these credentials to rebuild the request_object object
$new_request_object = $oauth->auth('twitter', array(
'credentials' => $credentials
));
// Retrieve the credentials and save them
var credentials = request_object.getCredentials();
// Later use these credentials to rebuild the request_object object
request_object = oauth.auth('twitter', {
credentials: credentials
});
Not available for this SDK
For back end SDKs you can to rebuild the request object after having saved the credentials (set of access token, refresh tokens, etc.) manually.
Refreshing the tokens
# Using a backend https://oauth.io/auth/refresh_token/:provider Body: token: REFRESH_TOKEN key: PUBLIC_OAUTHIO_KEY secret: SECRET_OAUTHIO_KEY
OAuth.refreshCredentials(oauthResult, req.session)
.then(function(newOAuthResult) {
//todo with newOAuthResult
})
.fail(function(e) {
//handle an error
});
});
//or from session
OAuth.auth('facebook', req.session, {
force_refresh: true
})
// The auth method automatically refreshes the tokens if needed
$request_object = $oauth->auth('facebook', array(
'credentials' => $credentials
));
For most providers, the server side authorization sends back a refresh token without any specific configuration. The refresh token is added to the result on a server-side authorization only.
This refresh token can be used when an access token expires to regenerate one without having to open a popup and ask your user for permissions (as the user has already accepted them).
In all our server-side SDK, a method is available to manually refresh the access token. It gives back a new request object containing a fresh access token.
For the Google provider, it's a bit more complex. To get a refresh token, please follow this Stackoverflow link: http://stackoverflow.com/questions/23759138/getting-refresh-tokens-from-google-with-oauth-io
Request objects
with Facebook (OAuth 2)
{
"access_token": "CAAHv0hYN...RmO4zcd",
"expires_in": 5183561,
"provider": "facebook"
}
with Twitter (OAuth 1.0a)
{
"oauth_token": "9568514...0AQMedh",
"oauth_token_secret": "Ktakg008...60KSNG4",
"provider": "twitter"
}
with Google using the server side flow with a frontend SDK
{
"code": "XsrpW...leE3",
"provider": "google"
}
with Github using the server side flow in a backend SDK
{
"provider": "github",
"access_token": "akpWg0...QEof",
"refresh_token": "HvOiruf...Zriv",
"expires_in": 5183561
}
We call request object the result object you get after an authorization. It lets you access the tokens, expiry date etc. but also gives you simple methods to access others OAuth.io API (Make authorized API call to the provider, retrieve unified user data, and more). The request object will contains these fields:
Field | Description | Type | Example value |
---|---|---|---|
access_token | OAuth 2 -- The authorization key to access the OAuth2 API | string | CAAHv...aAWy |
oauth_token | OAuth 1 -- The authorization key to access the OAuth1 API | string | XVQpX...WR0K |
oauth_token_secret | OAuth 1 -- The second authorization key to access OAuth1 API | string | PHQD2...V7xw |
expires_in | Optional depending the provider -- The expiration of the access_token |
integer | 5184000 |
code | Client side only -- The code to be exchanged against the access token server side authorization | string | XsrpW...leE3 |
refresh_token | Server side only -- The refresh token is used to refresh the access_token to extend the expiration. | string | Tgfgso |
provider | The provider your user is connected with | string |
The access token can be sent to your backend to make API calls but, you can't be sure that the access token is a real one (as the user could fake a request with a wrong access token) so you need to make a test API call and see if it returns 200 (OK) or 401 (UNAUTHORIZED).
As you can see, using the client side authorization, you won't have a refresh_token
. For this, please take a look at the Server side authorization
section.
Request API
OAuth.auth(provider, req.session).then(function(oauthResult) {
return oauthResult.get('/me')
}).then(function(data) {
//data is the result of the request to /me
}).fail(function(err) {
//handle an error
});
$me = $request_object->get('/me');
OAuth.popup(provider).then(function(oauthResult) {
return oauthResult.get('/me');
}).then(function(data) {
// data is the result of the request to /me
}).fail(function(err) {
// handle an error
});
// In a
- (void)didReceiveOAuthIOResponse:(OAuthIORequest *)request
{
// The request object
_request_object = request;
// Making a request
[_request_object get:@"/me" success:^(NSDictionary *output, NSString *body, NSHTTPURLResponse *httpResponse)
{
// logs the the user's information
NSLog(@"%@", body);
}];
}
data.http("/me", new OAuthRequest() {
@Override
public void onSetURL(String _url) {
// This method is called once the final url is returned.
}
@Override
public void onSetHeader(String header, String value) {
// This method is called for each header to add to the request.
}
@Override
public void onReady() {
// This method is called once url and headers are set.
}
@Override
public void onError(String message) {
// This method is called if an error occured
}
});
The Request API allows you to easily perform authorized API calls to the OAuth provider from which you got a request object or credentials with the Token API. You can perform classic HTTP calls using GET, POST, PUT, DELETE, PATCH. OAuth.io will automatically fill all authorization parameters for you (OAuth1 signature, nonce, timestamp, access_token, oauth_token etc...). All the parameters in the request will be sent to the provider thanks to the oauth.io proxy.
data.http(new OAuthJSONRequest(OAuthJSONRequest.HTTP_GET, "/me"), new OAuthJSONCallback() {
@Override
public void onFinished(JSONObject data) {
// data is the result of the request to /me
}
@Override
public void onError(String message) {
// handle an error
}
});
GET
oauthResult.get(url).then(function(data) {
//todo with data
}).fail(function(err) {
//todo with err
});
oauthResult.get(url).done(function(data) {
//todo with data
}).fail(function(err) {
//todo with err
});
$me = $request_object->get('/me');
// Making a request
[_request_object get:@"/me" success:^(NSDictionary *output, NSString *body, NSHTTPURLResponse *httpResponse)
{
// logs the the user's information
NSLog(@"%@", body);
}];
// See http method
Allows you to perform GET
request to an API endpoint
Argument | Description | Type | Example value |
---|---|---|---|
url | The URL of the endpoint, it can be an absolute URL or just the endpoint (after the domain) as for most provider, the domain is already known | string | /api/endpoint?param=value |
POST
oauthResult.post(url, params).done(function(data) {
//todo with data
}).fail(function(err) {
//todo with err
});
// params has the same syntaxe as jQuery.ajax (http://api.jquery.com/jquery.ajax/)
//e.g Post a tweet on Twitter
oauthResult.post('/1.1/statuses/update.json', {
data: {
status: "hello world!"
}
})
oauthResult.post(url, params).done(function(data) {
//todo with data
}).fail(function(err) {
//todo with err
});
//e.g Post a tweet on Twitter
oauthResult.post('/1.1/statuses/update.json', {
status: "hello world!"
});
$request_object->post('/me/feed', array(
'message' => 'Hello world'
));
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setValue:@"Hello world" forKey:@"message"];
[_request post:@"/me/feed" withParams:data success:^(NSDictionary *output, NSString *body, NSHTTPURLResponse *httpResponse)
{
NSLog(@"%@", body);
}];
// See http method
Allows you to perform POST
request to an API endpoint
Argument | Description | Type | Example value |
---|---|---|---|
url | The URL of the endpoint, it can be an absolute URL or just the endpoint (after the domain) as for most provider, the domain is already known | string | /api/endpoint |
params | The parameters of the HTTP request | Object |
PUT
oauthResult.put(url, params).done(function(data) {
//todo with data
}).fail(function(err) {
//todo with err
});
//e.g Merge a pull request on Github
oauthResult.put('/repos/oauth-io/oauthd/pulls/5/merge')
oauthResult.put(url, params).done(function(data) {
//todo with data
}).fail(function(err) {
//todo with err
});
//e.g Merge a pull request on Github
oauthResult.put('/repos/oauth-io/oauthd/pulls/5/merge');
$request_object->put('/some/endpoint', array(
'name' => 'My updated name'
));
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setValue:@"My updated name" forKey:@"message"];
[_request put:@"/some/endpoint" withParams:data success:^(NSDictionary *output, NSString *body, NSHTTPURLResponse *httpResponse)
{
NSLog(@"%@", body);
}];
// See http method
Allows you to perform PUT
request to an API endpoint
Argument | Description | Type | Example value |
---|---|---|---|
url | The URL of the endpoint, it can be an absolute URL or just the endpoint (after the domain) as for most provider, the domain is already known | string | /api/endpoint |
params | The parameters of the HTTP request | Object |
DELETE
oauthResult.del(url).then(function(data) {
//todo with data
}).fail(function(err) {
//todo with err
});
//e.g Delete a status on Facebook
oauthResult.del('/v2.2/:status_id')
$request_object->del('/some/endpoint/someid');
[_request del:@"/some/endpoint/someid" success:^(NSDictionary *output, NSString *body, NSHTTPURLResponse *httpResponse)
{
NSLog(@"%@", body);
}];
// See http method
Allows you to perform DELETE
request to an API endpoint
Argument | Description | Type | Example value |
---|---|---|---|
url | The URL of the endpoint, it can be an absolute URL or just the endpoint (after the domain) as for most provider, the domain is already known | string | /api/endpoint |
PATCH
oauthResult.patch(url, params).done(function(data) {
//todo with data
}).fail(function(err) {
//todo with err
});
// params has the same syntaxe as jQuery.ajax (http://api.jquery.com/jquery.ajax/)
//e.g Edit a Gist on Github
oauthResult.patch('/gists/1', {
data: {
"description": "the description for this gist",
"files": {
"file1.txt": {
"content": "updated file contents"
},
"new_file.txt": {
"content": "a new file"
}
}
}
})
oauthResult.put(url, params).done(function(data) {
//todo with data
}).fail(function(err) {
//todo with err
});
//e.g Merge a pull request on Github
oauthResult.patch('/gists/1', {
"description": "the description for this gist",
"files": {
"file1.txt": {
"content": "updated file contents"
},
"new_file.txt": {
"content": "a new file"
}
}
});
$request_object->patch('/some/endpoint', array(
'name' => 'My updated name'
));
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setValue:@"My updated name" forKey:@"message"];
[_request patch:@"/some/endpoint" withParams:data success:^(NSDictionary *output, NSString *body, NSHTTPURLResponse *httpResponse)
{
NSLog(@"%@", body);
}];
// See http method
Allows you to perform PATCH
request to an API endpoint
Argument | Description | Type | Example value |
---|---|---|---|
url | The URL of the endpoint, it can be an absolute URL or just the endpoint (after the domain) as for most provider, the domain is already known | string | /api/endpoint |
params | The parameters of the HTTP request | Object |
USING REST
#Example with twitter on /1.1/account/verify_credentials.json GET /request/twitter/%2F1.1%2Faccount%2Fverify_credentials.json HTTP/1.1 Host: oauth.io oauthio: k=OAUTHIO_PUBLIC_KEY&oauthv=1&oauth_token=TWITTER_PUBLIC_TOKEN&oauth_token_secret=TWITTER_SECRET_TOKEN Referer: https://whitelisted_domain_in_oauthio/
GET|POST|PUT|DELETE|PATCH https://oauth.io/request/:provider/:url
Field | Description |
---|---|
provider | The provider's name (e.g. "facebook") |
url | The api request's url, can be relative to the main api domain (e.g api.facebook.com ) or absolute. This url must be urlencoded. |
You must include the oauthio
HTTP header inside your request, which is a application/x-www-form-urlencoded hash containing:
Field | Description |
---|---|
k | The public OAuth.io key of your app. If the http header Origin or Referer is set, this will be checked against your app's whitelist. If none are present, you must accept the "localhost" domain in your OAuthio's app. |
oauth_token | OAuth1 public token. |
oauth_secret_token | OAuth1 secret token. |
access_token | OAuth2 token. |
oauthv (optional) | when a provider supports both OAuth1 and OAuth2, this can be set to "1" or "2" to desambiguate the version of OAuth to use. |
User Data API
Usage
res = OAuth.create('facebook');
res.me().done(function(me) {
alert('Hello ' + me.name);
}).fail(function(err) {
//todo when the OAuth flow failed
});
oauth.popup("facebook", new OAuthCallback() {
@Override
public void onFinished(OAuthData data) {
if (data.status.equals("error"))
activity.displayError(data.error);
else {
data.me(new OAuthJSONCallback() {
@Override
public void onFinished(JSONObject me) {
display(me.getString("name"));
}
@Override
public void onError(String message) {
}
});
}
}
});
This API allows you to retrieve your user's data in a unified way. This means you don't have to make a bridge between APIs to retrieve user's info, all fields sent are unified and described here. Filters can be added to retrieve a subset of these unified fields.
The endpoint is accessible using REST
GET https://oauth.io/auth/:provider/me
Fields
{
"id": "1234",
"name": "John Doe",
"firstname": "John",
"lastname": "Doe",
"alias": "john87",
"email": "john@doe.com",
"birthdate": {
"day": 27,
"month": 11,
"year": 1987
},
"raw": {
[RAW RESULT]
}
}
Field | Description | Type | Example value |
---|---|---|---|
id | The user id -- This id is unique for a provider | string | "1234" |
name | The user's name | string | John Doe |
firstname | The user's firstname | string | John |
lastname | The user's lastname | string | Doe |
alias | The user's alias (or login) | string | john87 |
The user's email address | string | john@doe.com | |
birthdate | The user's birthday | Object | {day: 27, month: 11, year: 1987} |
gender | The user's gender. 0: male; 1: female | integer | 0 |
location | The user's last location | string | San Francisco |
local | The user's local | string | FR |
company | The user's company | string | Webshell |
occupation | The user's job occupation | string | developer |
raw | The unmodified provider's response with non unified field | Object |
User Management API
Installation
You need to click 'Enable the User Management' button in your OAuth.io dashboard in the Users Overview
tab.
users = new OAuthUsers(oauth);
User.signup(data).done(function(user) {
//todo with `user`
});
User.signup({
email: 'john.doe@gmail.com',
password: 'St0ngP4ssw0rd!',
firstname: 'John',
lastname: 'Doe',
company: 'X Corp',
age: 47
}).done(function(user) {
//here, your user is logged in
console.log(user.data.firstname);
}).fail(function(err) {
//todo with `err`
});
Hashtableinfos = new Hashtable<>();
infos.put("firstname", "John");
infos.put("lastname", "Doe");
infos.put("email", "john.doe@gmail.com");
infos.put("password", "St0ngP4ssw0rd!");
// ...
users.signup(infos, new OAuthUserCallback() {
@Override
public void onFinished() {
// receive your identity
OAuthUser id = users.getIdentity();
}
@Override
public void onError(String message) {
displayError(message);
}
});
With email/password
You can sign up your users using their email/password.
data
is an object that must contains:
- password
- firstname
- lastname
You can add other pieces of data if you wish (the structure is free).
OAuth.popup(provider).then(function(res) {
return User.signup(res)
}).done(function(user) {
//here, your user is logged in
console.log(user.data.firstname);
}).fail(function(err) {
//todo with err
});
// Callback from oauth.popup
public void onFinished(OAuthData data) {
if (data.status.equals("error"))
displayError(data.error);
else {
users.signup(data, new OAuthUserCallback() {
@Override
public void onFinished() {
// receive your identity
OAuthUser id = users.getIdentity();
}
@Override
public void onError(String message) {
displayError(message);
}
});
}
}
With social logins
You can also use the Token API to sign up your users with their social identity. provider
is the name of a provider on OAuth.io as facebook
, twitter
, google
and 100+ others.
The provider needs to have the User API enabled to work properly (you can see it when you add a new provider in your OAuth.io Dashbaord).
OAuth.popup('twitter').then(function(twitter) {
twitter.email = "john.doe@gmail.com";
return User.signup(twitter);
}).done(function(user) {
//todo with user
});
// Callback from oauth.popup
public void onFinished(OAuthData data) {
if (data.status.equals("error"))
displayError(data.error);
else {
Hashtable infos = new Hashtable<>();
infos.put("email", "john.doe@gmail.com");
// ...
users.signup(data, infos, new OAuthUserCallback() {
@Override
public void onFinished() {
// receive your identity
OAuthUser id = users.getIdentity();
}
@Override
public void onError(String message) {
displayError(message);
}
});
}
}
Handling errors
Some providers don't give their user's email in their API (it's the case of Twitter for instance). So, you have to ask your user for their email manually and setup the email.
Signin your users
Once your user has signed up, you can log them in with their email password or with one of the social identity the user attached to their account.
OAuth.io manages your user's session for you and gives a simple API to let you know if the user is still logged in or not.
In this version, the session expires after 6 hours of inactivity but we are working on making this expiration configurable.
User.signin(email, password).done(function(user) {
console.log(user.data.firstname);
}).fail(function(err) {
// email/password incorrect.
});
users.signin(email, password, new OAuthUserCallback() {
@Override
public void onFinished() {
// receive your identity
OAuthUser id = users.getIdentity();
}
@Override
public void onError(String message) {
displayError(message);
}
});
With email/password
OAuth.popup(provider).then(function(res) {
return User.signin(res);
}).done(function(user) {
console.log(user.data.firstname);
}).fail(function(err) {
//todo with err
});
// Callback from oauth.popup
public void onFinished(OAuthData data) {
if (data.status.equals("error"))
displayError(data.error);
else
users.signin(data, new OAuthUserCallback() {
@Override
public void onFinished() {
// receive your identity
OAuthUser id = users.getIdentity();
}
@Override
public void onError(String message) {
displayError(message);
}
});
}
With social logins
Note: For social logins, the signin and signup steps are exactly the same feature. If the user doesn't exist, it will automatically sign them up before signing them in.
Get the connected user
var user = User.getIdentity();
OAuthUser id = users.getIdentity();
From cache
When a user logs in, we store their identity (information, providers linked etc.) in a cookie. You can access this cached version instantly using the SDK with User.getIdentity()
.
It returns the same data structure as the API version: User.refreshIdentity()
.
User.refreshIdentity().done(function(user) {
//todo with user
})
OAuthUser user;
// ...
user.refreshIdentity(new OAuthUserCallback() {
@Override
public void onFinished() {
// user data updated
}
@Override
public void onError(String message) {
displayError(message);
}
});
From the API
Retrieve the latest change done to your user.
Know if the user is authenticated
if (User.isLogged()) {
//todo with authenticated user
}
else {
//todo with unauthenticated user
}
if (users.isLogged()) {
//todo with authenticated user
}
else {
//todo with unauthenticated user
}
This method will check if the authorization cookie has been detected in the user's browser. It returns true
or false
Update your user data
var user = User.getIdentity()
user.data.firstname = 'Thomas';
user.data.someData = {
a: 42,
b: "some string"
}
user.save().done(function() {
//todo when saved
}).fail(function(err) {
//handle `err``
});
OAuthUser user = users.getIdentity();
user.data.put("firstname", "Thomas");
user.data.put("someData", "some string");
user.saveIdentity(new OAuthUserCallback() {
@Override
public void onFinished() {
// user data saved
}
@Override
public void onError(String message) {
displayError(message);
}
});
You can update all your user's data. Once you are done, just use the save()
method to save your changes. Fields are freely structurable so you can name them as you wish (just a few fields name are protected for our use: _provider_*
).
Reset password (or lost password)
User.resetPassword(email).done(function() {
//email sent to the user containing a key
});
//then...
User.confirmResetPassword(newPassword, key);
users.resetPassword(email, new OAuthUserCallback() {
@Override
public void onFinished() {
// reset email sent
}
@Override
public void onError(String message) {
displayError(message);
}
});
The reset flow is used when a user tries to login and can't remember their password. It will send an email to the user with a key
(to check their identity using their email). If the user is able to input the code on another page, they can change their password using this key
.
Change password
Coming soon
This feature is not released yet but will be used to change the password of the user (this option is often in the setting page of an account). The user can use it if they knows their current password to confirm their identity.
var user = User.getIdentity();
user.changePassword(oldPassword, newPassword);
Attach social identity to an account
var user = User.getIdentity();
OAuth.popup('google').then(function(google) {
return user.addProvider(google);
}).done(function() {
//provider attached
//Your user is now able to signin with Google
});
// Callback from oauth.popup
public void onFinished(OAuthData data) {
if (data.status.equals("error"))
displayError(data.error);
else {
OAuthUser user = users.getIdentity();
user.addProvider(data.provider, new OAuthUserCallback() {
@Override
public void onFinished() {
// provider attached
// Your user is now able to signin with data.provider
}
@Override
public void onError(String message) {
displayError(message);
}
});
}
}
You can attach a social identity to an account easily. That means at the next signin, they will be able to signin with another configured provider. This way a user can securely connect with more than one provider.
Remove social identity to an account
var user = User.getIdentity();
user.removeProvider('google').done(function() {
//provider detached
});
OAuthUser user = users.getIdentity();
user.removeProvider("google", new OAuthUserCallback() {
@Override
public void onFinished() {
// provider detached from google
}
@Override
public void onError(String message) {
displayError(message);
}
});
A user can detach a social identity from their account. Once a provider is detached, the user won't be able to login with it again, they needs to re-attach it again to be able to login with it.
The list of providers attached to an account
var user = User.getIdentity();
console.log(user.providers)
OAuthUser user = users.getIdentity();
// providers list is available in user.providers
From cache
When a user logs in, we store a local version of the providers list attached to their account so you can access it directly in the user
object.
var user = User.getIdentity();
user.getProviders().done(function(providers) {
console.log(providers);
});
OAuthUser user;
// ...
user.getProviders(new OAuthUserCallback() {
@Override
public void onFinished() {
// providers list is available in user.providers
}
@Override
public void onError(String message) {
displayError(message);
}
});
From the API
You can also get this list from the API to be sure it's synchronized with the backend.
Logout
var user = User.getIdentity();
user.logout().done(function() {
//todo when logout
});
OAuthUser user = users.getIdentity();
user.logout(new OAuthUserCallback() {
@Override
public void onFinished() {
// user is logout and their token is expired
}
@Override
public void onError(String message) {
displayError(message);
}
});
You can log your user out from your application using the logout()
method. It will clear the session and the associated cache.
Contribute
You can contribute by cloning our oauthd repository, or any of our SDK's repositories on GitHub (please check this repository list) and making a pull request.
Issues
If you have any issue using OAuth.io, you can:
Open a QA on StackOverflow (with the mention of OAuth.io in the title).
Open a GitHub issue on the appropriate repository.
If the content is private, feel free to send us an email on support@oauth.io
You can ping us on Twitter with the mention @oauth_io
We try to be as reactive as possible on every channel, according to the support questions load, and to the chosen plan (paying customers have the priority on support).
Adding Providers to OAuth.io
You can easily add new OAuth providers in OAuth.io by using our configuration file format.
The format is explained here and you can find all the existing OAuth providers on our GitHub repository.
Once you've implemented your provider, you can test it using oauthd, the opensource version of OAuth.io and then, just make a pull request and we'll merge it into OAuth.io as soon as we can.
A provider contains 4 simple files:
- conf.json The OAuth provider's JSON file (e.g. facebook.json)
- settings.json - Some settings for users who want to add the OAuth provider in OAuth.io (e.g. the link and screenshot where developers can create an application with your provider)
- logo.png - The logo of the OAuth provider
- me.js (optional) - A file used to retrieve the user information in a unified way.
Pull request (bug fixes / providers / typos)
You're welcome to fork our repositories on GitHub to make pull requests. We'll review each of them, and integrate all the relevant changes in a future release.
In every repository, we have included notes in the README.md file to show you how to test your feature.
oauthd
Fork the repository to implement your feature / bug fixes.
You can use npm link
to use the oauthd
command anywhere in your console, and create test instances.
OAuth.io is an oauthd instance, so if you find and fix bugs in oauthd, the changes will also be on OAuth.io.
SDKs
You can fork all the SDKs from GitHub in your favorite language. Every SDK (except iOS for the moment) has a test suite than can be launched in a standard way to try your feature / bug fixes.
Documentation
You can fork all the documentation from GitHub. The content is in the source
folder. The main file is index.md