Was this helpful?

To protect your App Services application data, one of the steps you'll take is to authenticate your app's users. By ensuring that they are who they say they are, you can help ensure that your application's data is available in secure ways. After you've created permission rules that define access to your application and have associated these rules with users, you'll want to add code that authenticates your user, as described in this topic.

Note: You manage access to your application's data by creating permission rules that govern which users can do what. Users authenticated as Application User have access according to these rules. For more about managing permissions, see Managing access by defining permission rules.

Authentication levels

App Services supports four levels of authentication:

  • Application user: Grant's user access to an API Services application, based on the roles and permissions assigned to the user.
  • Application client: Grants full access to perform API requests against an API Services application.
  • Organization client: Grants full access to perform API requests against an API Services organization.
  • Admin user: Grants full access to perform API requests against any API Services organization that the user is an admin of.

Because the scope of access provided by the application client, organization client, and admin user authentication levels is so broad (and as a result, so powerful), it's a bad practice to use them from a mobile app or any client-side code. Instead, they're better suited to server-side implementations, such as web applications.

For a more detailed description of available authentication levels, see Authentication levels.

Application user authentication (user login)

Using the username and password values specified when the user entity was created, your app can connect to the App Services application endpoint to request an access token. It's also acceptable to use the user's email address in place of the username.

Using the SDKs

When a user is logged in using the Apigee iOS, JavaScript, node.JS and Android SDKs, the returned token is automatically stored in the ApigeeDataClient (iOS), DataClient (Android), or Apigee.Client (JavaScript/node.JS) class instance, and will be sent to the API with all subsequent method calls.

Request syntax

curl -X POST "https://api.usergrid.com/<orgName>/<appName>/token" -d '{"grant_type":"password", "username":<username>, "password":<password>}'

Example request

curl -X POST "https://api.usergrid.com/my-org/my-app/token" -d '{"grant_type":"password", "username":"john.doe", "password":"testpw"}'
		

Example response

The results include the access token needed to make subsequent API requests on behalf of the application user:

{
"access_token": "5wuGd-lcEeCUBwBQVsAACA:F8zeMOlcEeCUBwBQVsAACA:YXU6AAABMq0hdy4Lh0ewmmnOWOR-DaepCrpWx9oPmw",
"expires_in": 3600,
"user": {
	...
}
}
		

SDK method

(ApigeeClientResponse *)logInUser: (NSString *)userName password:(NSString *)password

Example request

//create an instance of AppDelegate
//we recommend you call ApigeeClient from your AppDelegate.
//for more information see the iOS SDK install guide:
//http://apigee.com/docs/app-services/content/installing-apigee-sdk-ios
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

//call longInUser to initiate the API call
ApigeeClientResponse *response = [appDelegate.dataClient logInUser:username password:password];
@try {
    //success - a token is returned in the response
}
@catch (NSException * e) {
    //fail - most likely a bad username/password
}			
		

Example response

{
    "access_token" = "YWMtsi9ERF_EeOUIOc3TUbToQAAAUKb_OPzZmpWk6J7hwUZyY3w6FEIRtw8psA";
    "expires_in" = 604800;
    user =     {
        activated = 1;
        created = 1384203732578;
        email = "user@yourapp.com";
        modified = 1384203732578;
        name = someuser;
        picture = "http://www.gravatar.com/avatar/2076105f6efe7c11e285add95f514b9a";
        type = user;
        username = someuser;
        uuid = "89469434-4b14-11e3-ae68-ff6ddb9bb1aa";
    };
}			
		

SDK method

authorizeAppUserAsync(final String email, final String password, final ApiResponseCallback callback)

Example request

//dataClient is your instance of the ApigeeClient class
dataClient.authorizeAppUserAsync(username, password, new ApiResponseCallback() {
	
	//If authorizeAppUserAsync fails, catch the error
	@Override
	public void onException(Exception e) { 
		// Error
	}
	
	//If successful, handle the response object
	@Override
	public void onResponse(ApiResponse response) {
	    try { 
	        if (response != null) {
	            // Success - access token is returned in the response
	        }
	    } catch (Exception e) {
	        	// Fail - most likely a bad username/password
	    }
    }
});				
		

Example response

{
   "rawResponse":"{"   access_token":"KlJAEeOE68s4qMeT8wAAAUKcCAYzmdaUteMnqjQ3o46uuwKhoz08WyIYWMt5A84",
   "expires_in":604800,
   "user":{
      "uuid":"89469434-4b14-11e3-ae68-ff6ddb9bb1aa",
      "type":"user",
      "name":"someuser",
      "created":1384203732578,
      "modified":1384203732578,
      "username":"someuser",
      email = "user@yourapp.com",
      "activated":true,
      "picture":"http://www.gravatar.com/avatar/2076105f6efe7c11e285add95f514b9a"
   }
}","user":{
   "dataClient":null,
   "email":"user@yourapp.com",
   "name":"someuser",
   "picture":"http://www.gravatar.com/avatar/2076105f6efe7c11e285add95f514b9a",
   "username":"someuser",
   "activated":true,
   "disabled":false,
   "type":"user",
   "uuid":"89469434-4b14-11e3-ae68-ff6ddb9bb1aa",
   "created":1384203732578,
   "modified":1384203732578
},
"timestamp":0,
"entityCount":0,
"firstEntity":null,
"lastEntity":null,
"access_token":"KlJAEeOE68s4qMeT8wAAAUKcCAYzmdaUteMnqjQ3o46uuwKhoz08WyIYWMt5A84",
"expires_in":604800
}			
		

The example assumes use of the JavaScript (HTML5) SDK.

SDK method

login(username, password, callback)

Example request

dataClient.login(username, password, function (error,response) {
        if (error) {
            //error — could not log user in
        } else {
            //success — user has been logged in
            var token = dataClient.token;
        }
    }
);
		

Example response

Object {access_token: "hFLaEeOVvSEuHOLs0wAAAUKf83n9O4Tll-djK8Ghq5GdHIQZ7xrpoOsYWMtAWpO", expires_in: 604800, user: Object}
	access_token: "hFLaEeOVvSEuHOLs0wAAAUKf83n9O4Tll-djK8Ghq5GdHIQZ7xrpoOsYWMtAWpO"
	expires_in: 604800
	user: Object
		activated: true
		created: 1384203732578
		email: "user@yourapp.com"
		modified: 1384203732578
		name: "someuser"
		picture: "http://www.gravatar.com/avatar/2076105f6efe7c11e285add95f514b9a"
		type: "user"
		username: "someuser"
		uuid: "89469434-4b14-11e3-ae68-ff6ddb9bb1aa"
		__proto__: Object
__proto__: Object
		

The example assumes use of the Ruby SDK.

SDK method

login (username, password)

Example request

app = Usergrid::Application.new 'https://api.usergrid.com/my-org/my-app/'
app.login username, password
token = app.auth_token
		

Example response

		
{
   "access_token":"elLbEeOo8v2Z0bwpxQAAAUKf-xnbGtl3gehLTR9NWV26bPlQ0XMeW5oYWMtKz8N",
   "expires_in":604800,
   "user":{
      "uuid":"89469434-4b14-11e3-ae68-ff6ddb9bb1aa",
      "type":"user",
      "name":"someuser",
      "created":1384203732578,
      "modified":1384203732578,
      "username":"someuser",
      "email":"user@yourapp.com",
      "activated":true,
      "picture":"http://www.gravatar.com/avatar/2076105f6efe7c11e285add95f514b9a"
   }
}
		

The example assumes use of the Node.js module.

SDK method

login(username, password, callback)

Example request

var username = 'testuser';
var password = 'testpasswd';
dataClient.login(username, password, function (error, response) {
        if (error) {
            //error — could not log user in
        } else {
            //success — user has been logged in
            var token = client.token;
        }
    }
);
		

Example response

{ access_token: 'iFLbEeOyfrF-3pXAxgAAAUKf_4xzyktaBBm8jmP4bnbd9avblkB14CMYWMt2Ptx',
  expires_in: 604800,
  user:
   { uuid: '89469434-4b14-11e3-ae68-ff6ddb9bb1aa',
     type: 'user',
     name: 'someuser',
     created: 1384203732578,
     modified: 1384203732578,
     username: 'someuser',
     email: 'user@yourapp.com',
     activated: true,
     picture: 'http://www.gravatar.com/avatar/2076105f6efe7c11e285add95f514b9a' } 
}			
		

Application client authentication

Using your app’s client id and client secret values, your app can connect to the App Services application endpoint to request an access token. The client ID and secret for your app can be found in 'Getting Started' section of the API Services admin portal, under 'Server App Credentials'.

Warning: You should never authenticate this way from a client-side app such as a mobile app. A hacker could analyze your app and extract the credentials for malicious use even if those credentials are compiled and in binary format. See "safe mobile access" in Authenticating API requests for additional considerations in keeping access to your app and its data secure.

Request syntax

curl -X POST "https://api.usergrid.com/<orgName>/<appName>/token" -d '{"grant_type":"client_credentials", "client_id":<application_clientID>, "client_secret":"<application_client_secret>"}'

Example request

curl -X POST "https://api.usergrid.com/my-org/my-app/token" -d '{"grant_type":"client_credentials", "client_id":"YXB7NAD7EM0MEeJ989xIxPRxEkQ", "client_secret":"YXB7NAUtV9krhhMr8YCw0QbOZH2pxEf"}'
		

Example response

The results include the access token needed to make subsequent API requests on behalf of the application:

{
"access_token": "F8zeMOlcEeCUBwBQVsAACA:YXA6AAABMq0d4Mep_UgbZA0-sOJRe5yWlkq7JrDCkA",
"expires_in": 3600,
"application": {
...  
}
}
		

SDK method

Application.login_credentials(client_id,client_secret)

Example request

#Create a client object				
usergrid_api = 'https://api.usergrid.com'
organization = 'your-org'
application = 'your-app'
client_id = 'XDDE4kFHkO12EeKkN_UdQDp84g'
client_secret = 'DSE4frScUIfOZCU7_-CeRJgm-pvUaRo'

client = Usergrid::Application.new "#{usergrid_api}/#{organization}/#{application}"

begin
	# Call login_credentials to initiate the API call
	# and save the response
	response = client.login_credentials(client_id,client_secret)
rescue
	#fail
end			
		

Example response

{
	"access_token":"SDde04kfKpj9EeOJCI8033US_AAAAURrmlkoUvIejKsEDE1FpIfZDHXIfcdrchg",
	"expires_in":604800,
	"application":"524sd90-ed76-11e2-a437-f51d403a7ce2"
}			
		

SDK method

request(options, callback)

Example request

//initialize the SDK		
var dataClient = new Usergrid.client({
        orgName:'your-org',
        appName:'your-app',
    });

//options for the request
var options = {
	endpoint:"token", //management token endpoint
	method:"POST",
	body: {
		//our client credentials and OAuth grant type
	    client_id: 'b3U68vghI6FmDSCd34e4Gtzz0A',
	    client_secret: 'b3U6QPkNDDSedF4sel3MCJ0haHKynew',
	    grant_type: "client_credentials"
    }
}

dataClient.request(options, function (error, result) {

	if (error) { 
	    // Error
	} else { 
		// Success
	}

});			
		

Example response

{ access_token: 'YWMtXcSPBpkSDcfr95kF9-IhTgAAAURrtfFyUyP_0ESa3qQnarknlIIXY0BQrzA',
  expires_in: 604800,
  application: '5d554790-ed76-11e2-a437-f51dskd9er4e' }
		

Admin user authentication

If you do require admin user access, your app can connect to the App Services management endpoint to request an access token. Your app supplies the username and password of an admin user in the request.

Warning: Authenticating as an admin user grants full access to one or more organizations and all of the applications contained in those organizations. Due to this, be cautious when implementing this type of authentication in client-side code. Instead, consider implementing admin user access in server-side code only. See "safe mobile access" in Authenticating API requests for additional considerations in keeping access to your app and its data secure.

Request syntax

curl -X POST "https://api.usergrid.com/management/token" -d '{"grant_type":"password", "username":<admin_username>, "password":<admin_password>}'

Example Request

curl -X POST "https://api.usergrid.com/management/token"  -d '{"grant_type":"password", "username":"testadmin", "password":"testadminpw"}'

Example response

The results include the access token needed to make subsequent API requests on behalf of the admin user:

{
	"access_token": "f_GUbelXEeCfRgBQVsAACA:YWQ6AAABMqz_xUyYeErOkKjnzN7YQXXlpgmL69fvaA",
	"expires_in": 3600,
	"user": {
		...
	}
}		    
		

SDK method

(ApigeeClientResponse *)apiRequest: (NSString *)url operation:(NSString *)op data:(NSString *)opData

Example request

//create an instance of AppDelegate
//we recommend you call ApigeeClient from your AppDelegate.
//for more information see the iOS SDK install guide:
//http://apigee.com/docs/app-services/content/installing-apigee-sdk-ios
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

NSString *url = @"https://api.usergrid.com/management/token";
NSString *op = @"POST";

//Retrieve user credentials from input. Never hard code.
NSString *username;
NSString *password;

//construct the body of our request
NSString *options = [NSString stringWithFormat:@"%@%@%@%@%@", @"{\"username\":\"", username, @"\",\"password\":\"", password, @"\",\"grant_type\":\"password\"}"];

ApigeeClientResponse *response = [appDelegate.dataClient apiRequest:url operation:op data:options];

@try {
    NSLog(@"%@",response.response);
    
}
@catch (NSException * e) {
    NSLog(@"false");
    
}			
		

Example response

{
    "access_token" = "YWMtx2aSdtrwEeOAsG_KkyBJVSDC45fsr5xNF5f9aUf-nk7saByvfij39vVb2pA";
    "expires_in" = 604800;
    passwordChanged = 1380058452528;
    user =     {
        activated = 1;
        adminUser = 1;
        applicationId = "00000000-0000-0000-0000-000000000001";
        confirmed = 1;
        disabled = 0;
        displayEmailAddress = "someUser <someUser@yourcompany.com>";
        email = "someUser@yourcompany.com";
        htmldisplayEmailAddress = "someUser <someUser@yourcompany.com>";
        name = someUser;
        organizations =         {
            someOrg =             {
                applications =                 {
                    "someOrg/someApp" = "b9f298c0-3797-11e3-badf-87e30cd375d2";
                    "someOrg/someOtherApp" = "5d554790-ed76-11e2-a437-f51d403a7ce2";
                };
                name = someOrg;
                properties =                 {
                };
                users =                 {
                    someUser =                     {
                        activated = 1;
                        adminUser = 1;
                        applicationId = "00000000-0000-0000-0000-000000000001";
                        confirmed = 1;
                        disabled = 0;
                        displayEmailAddress = "someUser ";
                        email = "someUser@yourcompany.com";
                        htmldisplayEmailAddress = "someUser <someUser@yourcompany.com>";
                        name = someUser;
                        properties =                         {
                            passwordPolicyId = 15;
                        };
                        username = someUser;
                        uuid = "s87fm423-a166-11e2-a7f7-02e81sid9fr3";
                    };
                };
                uuid = "s87fm423-a166-11e2-a7f7-02e81sid9fr3";
            };
        };
        properties =         {
            passwordPolicyId = 15;
        };
        username = someUser;
        uuid = "f25sdfr3w-a166-11e2-a7f7-02e81adcf3d0";
    };
}			
		

Admin user authentication is currently not supported by the Apigee Android SDK.

SDK method

request(options, callback)

Example request

//Initialize the SDK
var dataClient = new Apigee.Client({
    orgName:'your-org',
    appName:'your-app',
});

//Retrieve user credentials from input. Never hard code.
var username;
var password;
    
//options for the request
var options = {
	endpoint:'management/token', //management token endpoint
	method:'POST',
	mQuery: true, //specifies that we are not targeting an orgName/appName endpoint
	body: {
		//our user credentials and OAuth grant type
	    username: username,
	    password: password,
	    grant_type: 'password'
    }
}

dataClient.request(options, function (error, result) {

	if (error) { 
	    // Error
	} else { 
		// Success
	}

});
		

Example response

Object {passwordChanged: 1380058452528, access_token: "YWDfetkz8pjTEeOU8KtgtjfgWwAAAURqhwtqePwhRrB61u2CB665tRGBJ184Iek", expires_in: 604800, user: Object}
access_token: "YWDfetkz8pjTEeOU8KtgtjfgWwAAAURqhwtqePwhRrB61u2CB665tRGBJ184Iek"
expires_in: 604800
passwordChanged: 1380058452528
user: Object
	activated: true
	adminUser: true
	applicationId: "00000000-0000-0000-0000-000000000001"
	confirmed: true
	disabled: false
	displayEmailAddress: "someUser "
	email: "someUser@yourcompany.com"
	htmldisplayEmailAddress: "someUser <someUser@yourcompany.com>"
	name: "someUser"
organizations: Object
	someOrg: Object
	someOtherOrg: Object
__proto__: Object
properties: Object
	username: "someUser"
	uuid: "f2935781-a166-11e2-a7f7-02e81adcf3d0"
__proto__: Object
__proto__: Object			
		

The example assumes use of the Ruby SDK.

SDK method

//Targets the /management endpoint
Usergrid::Management.new <base_url>
//Performs the admin user login
login <username>, <password>
		

Example Request

mgmt = Usergrid::Management.new 'https://api.usergrid.com/'
mgmt.login username, password
token = mgmt.auth_token
		

Example response

{
  "action" : "get admin user",
  "status" : "ok",
  "data" : {
    "organizations" : {
      "someOrg" : {
        "users" : {
          "someUser" : {
            "applicationId" : "00000000-0000-0000-0000-000000000001",
            "username" : "someUser",
            "name" : "someUser",
            "email" : "someUser@yourcompany.com",
            "activated" : true,
            "confirmed" : true,
            "disabled" : false,
            "properties" : {
              "passwordPolicyId" : 15
            },
            "uuid" : "sk9d8vfr-a166-11e2-a7f7-02e81adcf3d0",
            "adminUser" : true,
            "displayEmailAddress" : "someUser <someUser@yourcompany.com>",
            "htmldisplayEmailAddress" : "someUser <<a href=\"mailto:someUser@yourcompany.com\">someUser@yourcompany.com</a>>"
          },
        },
        "name" : "someUser",
        "applications" : {
          "someUser/someApp" : "5d554790-ed76-11e2-a437-sk9d8vfr7ce2",
        },
        "properties" : { },
        "uuid" : "sk9d8vfr-a166-11e2-a7f7-02e81adcf3d0"
      }
    },
    "applicationId" : "00000000-0000-0000-0000-000000000001",
    "properties" : {
      "passwordPolicyId" : 15
    },
    "htmldisplayEmailAddress" : "someUser <someUser@yourcompany.com>",
    "username" : "someUser",
    "confirmed" : true,
    "token" : "YWMtfrW-xSD9fkErfe_DIYAtTAAASDCci9rfxbicVvX4S5W5jie5wc55D9seD5k",
    "email" : "someUser@yourcompany.com",
    "adminUser" : true,
    "name" : "someUser",
    "activated" : true,
    "uuid" : "sk9d8vfr-a166-11e2-a7f7-02e81adcf3d0",
    "displayEmailAddress" : "someUser ",
    "disabled" : false
  },
  "timestamp" : 1392763155175,
  "duration" : 110
}

		

The example assumes use of the Node.js module.

SDK method

request(options, callback)

Example request

//initialize the SDK
var dataClient = new Usergrid.client({
    orgName:'your-org',
    appName:'you-app',
});

//Retrieve user credentials from input. Never hard code.
var username;
var password;

//options for the request
var options = {
	endpoint:"management/token", //management token endpoint
	method:"POST",
	mQuery: true, //specifies that we are not targeting an orgName/appName endpoint
	body: {
		//our user credentials and OAuth grant type
	    username: username,
	    password: password,
	    grant_type: "password"
    }
}

//the actual API call
dataClient.request(options, function (error, result) {

	if (error) { 
	    // Error
	} else { 
	console.log(result);
		// Success
	}

});		

Example response

Note that the organizations the user has access to are returned in the organizations property.

{ passwordChanged: 1380058452528,
  access_token: 'YSDFrlPA8pjWEeOEvE96qf4eJgAAAURqmyDw2y5JcsEtsIUEt8V0xYsmVkP-MlY',
  expires_in: 604800,
  user: 
   { organizations: { someOrg: [Object], someOtherOrg: [Object] },
     applicationId: '00000000-0000-0000-0000-000000000001',
     properties: { passwordPolicyId: 15 },
     htmldisplayEmailAddress: 'someUser <<a href="mailto:user@yourcompany.com">user@yourcompany.com</a>>',
     username: 'someUser',
     confirmed: true,
     email: 'user@yourcompany.com',
     adminUser: true,
     name: 'someUser',
     activated: true,
     uuid: 'f2936541-a166-11e2-a7f7-02e81adcf3d0',
     displayEmailAddress: 'someUser ',
     disabled: false } }			
		

Organization client authentication

If you do require organization level access, your app can connect to the App Services management endpoint to request an access token. Access to an organization requires the client id and client secret credentials. The client ID and secret for your organization can be found on the 'Org Administration' page of the API Services admin console under 'Organization API Credentials'.

Warning: You should never authenticate this way from a client-side app such as a mobile app. A hacker could analyze your app and extract the credentials for malicious use even if those credentials are compiled and in binary format. See "safe mobile access" in Authenticating API requests for additional considerations in keeping access to your app and its data secure.

Request syntax

curl -X POST "https://api.usergrid.com/management/token" -d '{"grant_type":"client_credentials", "client_id":<org_clientID>, "client_secret":<org_client_secret>}'

Example request

curl -X POST "https://api.usergrid.com/management/token" -d '{"grant_type":"client_credentials", "client_id":"YXB7NAD7EM0MEeJ989xIxPRxEkQ", "client_secret":"YXB7NAUtV9krhhMr8YCw0QbOZH2pxEf"}'
	

Example response

The results include the access token needed to make subsequent API requests to the organization:

{
	"access_token": "gAuFEOlXEeCfRgBQVsAACA:b3U6AAABMqz-Cn0wtDxxkxmQLgZvTMubcP20FulCZQ",
	"expires_in": 3600,
	"organization": {
		...
	}
}
	    
		

SDK method

Organization.login_credentials(client_id, client_secret)

Example request

#Create a client object
usergrid_api = 'https://api.usergrid.com/management'
client_id = 'ks8dfFgrI6FmEeKn9wLoGtzz0A'
client_secret = 'so309dfFkJj0O5tCel3MCJ0haHKynew'

client = Usergrid::Organization.new "#{usergrid_api}"

begin
	# Call login_credentials to initiate the API call
	response = client.login_credentials(client_id,client_secret)
rescue
	#fail
end		
		

Example response

{
  "access_token": "YWMt-SDE9df-EeOyde1l_ts0AwAAAURrpjskIfMxjsdZ04S_2_nK5PLPUJyske4",
  "expires_in": 604800,
  "organization": {
    "users": {
      "someUser": {
        "applicationId": "00000000-0000-0000-0000-000000000001",
        "username": "someUser",
        "name": "someUser",
        "email": "someUser@yourcompany.com",
        "activated": true,
        "confirmed": true,
        "disabled": false,
        "properties": {
          "passwordPolicyId": 15
        },
        "uuid": "f2903878-a166-11e2-a7f7-02e81xod04rf",
        "adminUser": true,
        "displayEmailAddress": "someUser <someUser@yourcompany.com>",
        "htmldisplayEmailAddress": "someUser <<a href=\"mailto:someUser@yourcompany.com\">someUser@yourcompany.com<\/a>>"
      }
    },
    "name": "someOrg",
    "applications": {
      "someUser\/someApp": "s994kdf0-ed76-11e2-a437-f51d403a7ce2",
      "someUser\/someOtherApp": "slde3320-d7a8-11e2-9ce3-f315e5aa568a",
    },
    "uuid": "ddle04r3-a166-11e2-a7f7-02e81adcf3d0",
    "properties": {
      
    },
    "passwordHistorySize": 0
  }
}			
		

SDK method

request(options, callback)

Example request

//initialize the SDK		
var dataClient = new Usergrid.client({
        orgName:'your-org',
        appName:'your-app',
    });

//options for the request
var options = {
	endpoint:"management/token", //management token endpoint
	method:"POST",
	mQuery: true, //specifies that we are not targeting an orgName/appName endpoint
	body: {
		//our client credentials and OAuth grant type
	    client_id: 'b3U68vghI6FmDSCd34e4Gtzz0A',
	    client_secret: 'b3U6QPkNDDSedF4sel3MCJ0haHKynew',
	    grant_type: "client_credentials"
    }
}

dataClient.request(options, function (error, result) {

	if (error) { 
	    // Error
	} else { 
		// Success
	}

});			
		

Example response

{ access_token: 'YWMtWVds34RDeXOMqbeSTFNLYQAAAURrr0bJMH1fvTGTT1Ddrclr_T3L4jLI6-8',
  expires_in: 604800,
  organization: 
   { users: 
      { someUser: [Object] },
     name: 'someOrg',
     applications: 
      { 'someOrg/someApp': 'sk8dfvew-ed76-11e2-a437-f51d403a7ce2',
        'someOrg/someOtherApp': 'sld90fre-d7a8-11e2-9ce3-f315e5aa568a',
     uuid: 's00ddf4w-a166-11e2-a7f7-02e81adcf3d0',
     properties: {},
     passwordHistorySize: 0 } }			
		

An access token has a “time-to-live” (ttl), which is the maximum time that the access token will be valid for use within the application. With the API Baas, you can change the default ttl for all application user tokens, set the ttl for an individual token at the time of creation, or revoke one or more tokens. This gives you a high degree of control over access to your API Baas account and data store.

[toc]

Default ttl

By default, all tokens have a system-defined time-to-live of 7 days (604800 seconds). Note that Token ttl is specified in milliseconds, but when a token is created, the API response will return the ttl in seconds.

Changing the default ttl

You can change the default ttl for all application user tokens (that is, tokens associated with a user entity) by updating the application entity’s accesstokenttl property. Changing the default ttl will only affect new tokens. Any existing tokens will not be affected.

Please note that this does not apply to application client, organization client or admin user tokens. For more on obtaining tokens for these other authorization levels, see Authenticating users and application clients.

Note: If you set ttl=0, the token will never expire. This can pose a security risk and should be used with caution.

Request syntax

curl -X PUT https://api.usergrid.com/<org_name>/<app_name> -d '{"accesstokenttl":<ttl_in_milliseconds>}'

Example Request

curl -X PUT https://api.usergrid.com/your-org/your-app -d '{"accesstokenttl":"1800000"}'

Examples response

{
  "action" : "put",
  "application" : "d878de4r-99a7-11e3-b31d-5373d7165c2d",
  "params" : {
    "access_token" : [ "DFR4d5M1mJmoEeOGVPncm-g9qgAAAURv_lfQ7uu6aYHjJJn7QCrGoVnvU-ob5Ko" ]
  },
  "uri" : "https://api.usergrid.com/amuramoto/secured",
  "entities" : [ {
    "uuid" : "d878de4r-99a7-11e3-b31d-5373d7165c2d",
    "type" : "application",
    "name" : "your-org/your-app",
    "created" : 1392843003032,
    "modified" : 1392843615777,
    "accesstokenttl" : 1800000,
    "organizationName" : "your-org",
    "applicationName" : "your-app",
    "apigeeMobileConfig" : "{...}",
    "metadata" : {
      "collections" : [ "activities", "assets", "devices", "events", "folders", "groups", "roles", "users" ]
    }
  } ],
  "timestamp" : 1392843615767,
  "duration" : 28,
  "organization" : "your-org",
  "applicationName" : "your-app"
}

Changing ttl when a token is created

When you request an access token, you can override its ttl by including a ttl property in the body of the request when the token is created. This applies to tokens for all authentication levels, including application user, admin user, organization client, and application client authentication levels.

The ttl must be equal to or less than the value of the application entity's accesstokenttl property. If you specify a ttl value greater than the value of accesstokenttl, an error message is returned that indicates the maximum time to live value that can be specified.

For example, the following would create an application user token with a ttl of 180000000 milliseconds:

curl -X POST https://api.usergrid.com/your-org/your-app/token -d '{"username":"someUser", "password":"somePassword", "grant_type":"password", "ttl":"180000000"}'

Note: If you set ttl=0, the token will never expire. This can pose a security risk and should be used with caution.

Revoking tokens (user logout)

Under certain circumstances, you may need to explicitly revoke one or more tokens associated with a user entity, such as when a user logs out of your app. This is accomplished by making a PUT request to the /revoketoken and /revoketokens endpoints.

Request syntax

Revoke all tokens associated with a user entity

curl -X PUT https://api.usergrid.com/<org_name>/<app_name>/users/<user_uuid_or_username>/revoketokens
		

Revoke a specific token associated with a user entity

curl -X PUT https://api.usergrid.com/<org_name>/<app_name>/users/<user_uuid_or_username>/revoketoken?token=<token_to_revoke>			
		

Example request

curl -X PUT https://api.usergrid.com/your-org/your-app/users/someUser/revoketokens
		

Example response

{
  "action" : "revoked user token",
  "timestamp" : 1382050891455,
  "duration" : 24
}
		

Revoking admin user tokens

The /revoketoken and /revoketokens endpoints also work for revoking admin user tokens by making a PUT request to /management/users/<org_admin_username>/

Comments

Does the ttl parameter work for grant_type of password? Regardless of the value submitted I get back a token with a ttl of 604800. I was expecting a token that does not expire.
Example request:
curl -X POST -i -H "Content-Type: application/json" "https://api.usergrid.com/[org name]/[app name]/token?ttl=0" -d '{"grant_type":"password","username":"[username]","password":"[password here]"}'

Result:
{"access_token":"[token]","expires_in":604800,"user":{"uuid":"[uuid]","type":"user","name":"[User's name]","created":1383970356980,"modified":1383970356980,"username":"[username]","email":"[user email]","activated":true,"picture":"[image_link]"}}

Hi Andy

Apologies for the slow reply. This appears to be a bug. I am checking on the status of it and should have an answer for you soon.

-EDIT-

I've confirmed this is a bug. The syntax in the docs should work.

I have opened a ticket with our dev team to address it.

There doesn't seem to be an anchor on this page for the link "Safe mobile access" found in the paragraph above:
... See Safe mobile access for additional considerations in keeping access to your app and its data secure....

Should be fixed now. We'd moved the section and not updated links. Thanks Darius!

Add new comment

Provide your email address if you wish to be contacted offline about your comment.
We will not display your email address as part of your comment.

We'd love your feedback and perspective! Please be as specific as possible.
Type the characters you see in this picture. (verify using audio)

Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.