So you're building a native app?

                        (Or at least you should be)




                        Paul Madsen
                        Sr. Technical Architect


© 2010 Ping Identity Corporation
Agenda
•Drivers
•Very brief discussion of web vs native
•Authentication for native apps
•OAuth 2.0
•What does a client need to do to do
 OAuth?




© 2010 Ping Identity Corporation
© 2010 Ping Identity Corporation
© 2010 Ping Identity Corporation
© 2010 Ping Identity Corporation
Mobile Application Models
        Web Applications                   Native Applications

  Web Server                              Web Server


                   Mobile Web
                     Page


                                   HTML                 JSON/XML

  Mobile Device                           Mobile Device



                         Web App                       Native App


                        Browser


© 2010 Ping Identity Corporation
Native




Web

 © 2010 Ping Identity Corporation
Pros/cons




© 2010 Ping Identity Corporation
Native Applications Authentication

             Service Provider                                1. User trades credentials
                                                                for a token
                                                             2. Token delivered through
                                                                the browser to native
                                                                application
                                                             3. Native application
                        Token            Token                  presents token on API
            1                                            4      calls

          Password                                           4. API endpoint returns
                                     2
                                            3     JSON/XML      application data as
Device                                                          JSON/XML



                                                Native
                       Browser
                                                 App


  © 2010 Ping Identity Corporation
OAuth 2.0
– An open protocol to allow secure API authorization in a simple
  and standard method from desktop, mobile and web applications.
– Defines authorization & authentication framework for RESTful
  APIs
– Applied to delegated authorization – mitigates password anti-
  pattern - archetypical use case
– Provides a standard way to give a ‘key’ to a third-party which
  allows only limited access to perform specific functions without
  divulging your credentials




© 2010 Ping Identity Corporation
Native Mobile OAuth Options
•        DIY
         • Launching the browser (externally or embedded)
         • Detecting callback from the browser
         • JSON response parsing
         • Secure storage of persistent tokens

•        Use OAuth Client Library – Provides the above functionality with
         a higher level of abstraction. E.g.:
         • Google Toolbox for Mac - OAuth Controllers
             • http://code.google.com/p/gtm-
                 oauth/wiki/GTMOAuthIntroduction
         • Google APIs Client Library for Java
             • http://code.google.com/p/google-api-java-
                 client/downloads/detail?name=google-api-java-client-
                 1.4.1-beta.zip

•        (In Android) Android AccountManager
    © 2010 Ping Identity Corporation
                                                                            11
AccountManager

•As of Android 2.0,
AccountManager
manages accounts on
device
•Handles the OAuth 2.0
authorization flow on
behalf of applications
•Collects user consent
(as opposed to via a
browsert window)

  © 2010 Ping Identity Corporation
Android OAuth options
                                                          OAuth authz
     Device               App      Browser
                                                                                AS
                                                       API call w token
                                                                                RS
                                                 DIY & external browser


    Device                   Library                            OAuth authz
                    App
                                         Browser
                                                                                AS
                                                             API call w token
                                                                                RS

                                                       Use OAuth library & embedded browser

                                                          OAuth authz
    Device                App          Account                                  AS
                                       Manager
                                                       API call w token
                                                                                RS
                                                      AccountManager
© 2010 Ping Identity Corporation
Detailed walk through
•        For completeness, we'll show the DIY model
•       We'll show what the native application needs to
        do to
       1. Get user authenticated and get their authorization
       2. Obtain an access token
       3. Use that access token on an API call
       4. Get a fresh access token when the original expires




© 2010 Ping Identity Corporation
© 2010 Ping Identity Corporation
© 2010 Ping Identity Corporation
Getting a token overview


1. Open a browser and pass scopes
2. Deal with callback when it comes
3. Trade code for token




© 2010 Ping Identity Corporation
Native Mobile Client Integration
    Getting a Token

    •     Identify when a user needs to grant access to something at the Resource
          Server

    •     When this situation occurs, open a browser to:
             https://as.example.com/as/authorization.oauth2?c
             lient_id=<mobappclient_id>&response_type=code



Pre-requisites:                             Note: Additional query parameters are possible:
•   The partner OAuth Client must be        •   scope – space delimited (URL encoded as %20) requested
    defined in PingFederate config.             permissions of the client
•   Client must be assigned (at min.) the   •   state – an opaque value used by the partner to maintain state on
    Authorization Code grant type -             callback
    and thus a defined callback URL.        •   idp – custom parameter to request SAML IdP based authentication
•   IdP Adapter Mappings to                 •   pfidpadapterid – custom parameter to authenticate the user with a
    authenticate via an adapter                 named IdP Adapter


        © 2010 Ping Identity Corporation
                                                                                                                   18
Native Mobile Client Integration
Getting a Token (cont’d)

•     Open browser to authorization endpoint sample code:


- (IBAction)doAction:(id)sender
{
NSLog(@"About to open Safari to Oauth AS Authorization Endpoint...");


      // In this example, use a named IDP connection for user authentication
NSString* launchUrl =
@"https://as.pingidentity.com/as/authorization.oauth2?client_id=mobileclient1&respons
e_type=code&idp=https://idp.acme.com/saml-entity-id";


    [[UIApplicationsharedApplication] openURL:[NSURL URLWithString: launchUrl]];
}




    © 2010 Ping Identity Corporation
                                                                                        19
Comparison of grant types &
models


        Authorization Code (                                Resource Owner
        Embedded browser)                                     Credentials
                                           • No need to leave app context

                                                              • Password shared with 3rd party
                                                              • Application owns login UI
                                   • Enables SSO
                                   • Enables strong authn
                                   • AS owns login UI


                                       • Visual trust cues (SSL lock)
                                       • Authentication can leverage stored passwords
                                       • Authentication can leverage existing sessions

                                   Authorization Code
                                   (Separate browser)


© 2010 Ping Identity Corporation
Authenticating the user
• Talk about SSO options




© 2010 Ping Identity Corporation
© 2010 Ping Identity Corporation
Native Mobile Client Integration
Getting a Token (cont’d)

•     Authorization Page (default template):




                                               Requested
                                                 Scope




                                               Partner
                                               Details




    © 2010 Ping Identity Corporation
                                                           23
Native Mobile Client Integration
Getting a Token (cont’d)

• After the user authenticates and authorizes access at
  the Authorization Service, a callback (via HTTP redirect)
  will be made back to the Mobile Client Application.

• Approaches for callback to the native application:
   • Use a custom registered URI scheme (e.g.:
     mobileapp://oauth-callback?code=xxxx). (Example
     follows)
   • Use a custom registered MIME-type. A redirect
     would send the browser to a HTTP endpoint that
     responds with that content-type HTTP header (e.g.:
     Content-type: application/mobileapp).
 © 2010 Ping Identity Corporation
                                                              24
Native Mobile Client Integration
Getting a Token (cont’d)

•     Registering a custom URI scheme in iOS:




    © 2010 Ping Identity Corporation
                                                25
Native Mobile Client Integration
Getting a Token (cont’d)

•     Registering a custom URI scheme in Android:



    <activity android:name=".MyAppRegisterAccount" android:label="@string/addAccount" >
    <intent-filter>
    <action android:name="android.intent.action.VIEW"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <category android:name="android.intent.category.BROWSABLE"/>
    <data android:scheme="mymobileapp" />
    </intent-filter>
    </activity>




    © 2010 Ping Identity Corporation
                                                                                          26
Native Mobile Client Integration
Getting a Token (cont’d)

•     Receiving callback – sample code:


- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    // Schema based application call.
NSLog(@"Schema based call received.        URL: %@", url);


NSLog(@"Parsing query string...");
NSMutableDictionary *qsParms = [[NSMutableDictionaryalloc] init];
      for (NSString *param in [[url query] componentsSeparatedByString:@"&"]) {
NSArray *elts = [paramcomponentsSeparatedByString:@"="];
              if([elts count] < 2) continue;
              [qsParmssetObject:[elts objectAtIndex:1] forKey:[elts objectAtIndex:0]];
      };


// Process received URL parameters (code, error, etc.)...


    © 2010 Ping Identity Corporation
                                                                                         27
Native Mobile Client Integration
Getting a Token (cont’d)

•     Receiving callback – sample code:

@Override
public void onCreate(Bundle savedInstanceState)
{
// Could also be inside onNewInstance depending on the launchMode type
super.onCreate(savedInstanceState);
setContentView(R.layout.main);


        Intent intent = getIntent();
        Uri uri = intent.getData();


if (uri != null)
        {
                  // Callback from browser link / redirection
// Process received URL parameters (code, error, etc.)...
        }

    © 2010 Ping Identity Corporation
                                                                         28
Native Mobile Client Integration
Getting a Token (cont’d)

•     The following parameters are possible on the callback:
         •      code – the authorization code to resolve the OAuth token
         •      error – an error code (e.g.: access_denied)
         •      error_description– descriptive text about the error
         •      state – the same state value given in the original redirection

•     Callback processing:
         • The code callback parameter must be subsequentlyresolved
           into OAuth tokens by making a REST API call to the
           Authorization Server token endpoint .
         • If error is present in the callback, the application should
           gracefully fail and present a meaningful error to the user
           (possibly leveraging error_description).



    © 2010 Ping Identity Corporation
                                                                                 29
Native Mobile Client Integration
Getting a Token (cont’d)

•     Example token endpoint Request:



POST /as/token.oauth2 HTTP/1.1
Host: as.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8


grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA




    © 2010 Ping Identity Corporation
                                                                30
Native Mobile Client Integration
Getting a Token (cont’d)

•     Example token endpoint Response:



HTTP/1.1 200 OK
Content-Type: application/json;charset=UTF-8
Cache-Control: no-store
Pragma: no-cache


{"token_type":"Bearer","expires_in":60,"refresh_token":"uyAVrtyLZ2qPzI8rQ5
UUTckCdGaJsz8XE8S58ecnt8","access_token":"PeRTSD9RQrbiuoaHVPxV41MzW1qS"}




    © 2010 Ping Identity Corporation
                                                                             31
Native Mobile Client Integration
Getting a Token (cont’d)

•     Handling parameters – sample code:

        // Parse of URL query string complete
      if (error != nil) {
    // TODO: Show error message to user
      }
else {
NSString *code = [qsParmsobjectForKey:@"code"];


// Form HTTP POST to resolve JSON structure
NSString*post = [NSStringstringWithFormat:@"grant_type=authorization_code&code=%@",
code];
NSData*postData = [post
dataUsingEncoding:NSASCIIStringEncodingallowLossyConversion:YES];




    © 2010 Ping Identity Corporation
                                                                                      32
Native Mobile Client Integration
Getting a Token (cont’d)

•     Handling parameters – sample code (cont'd):

NSString*postLength = [NSStringstringWithFormat:@"%d",
                                       [postDatalength]];
NSMutableURLRequest *request = [[[NSMutableURLRequestalloc] init] autorelease];
              [requestsetURL:[NSURL URLWithString:@"https://as.idp.com/as/token.oauth2"]];
              [requestsetHTTPMethod:@"POST"];
[requestsetValue:postLengthforHTTPHeaderField:@"Content-Length"];
        [requestsetValue:@"application/x-www-form-urlencoded"
forHTTPHeaderField:@"Content-Type"];
              [requestsetHTTPBody:postData];


NSURLConnection *conn=[[NSURLConnectionalloc] initWithRequest:requestdelegate:self];
              if (conn) {
receivedData = [[NSMutableData data] retain];
              }
}


    © 2010 Ping Identity Corporation
                                                                                             33
Native Mobile Client Integration
Getting a Token (cont’d)

•     Handling parameters – sample code (cont'd):

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
     // json-framework library: https://github.com/stig/json-framework/
SBJsonParser*jsonParser = [[SBJsonParseralloc] init];
NSString*aStr = [[NSStringalloc] initWithData:receivedDataencoding:NSASCIIStringEncoding];
NSString*accessToken = nil;
NSString*refreshToken = nil;


id object = [jsonParserobjectWithString:aStr];
if (object) {
NSLog(@"JSON parsed successfully.");


if ([object isKindOfClass:[NSDictionary class]]) {
NSDictionary *nsDict = (NSDictionary*)object;
accessToken = [nsDictobjectForKey:@"access_token"];
refreshToken = [nsDictobjectForKey:@"refresh_token"];
           }



    © 2010 Ping Identity Corporation
                                                                                             34
Native Mobile Client Integration
Getting a Token (cont’d)

•     Handling parameters – sample code:

        // Callback from browser link / redirection
String code = uri.getQueryParameter("code");
String error = uri.getQueryParameter("error");


if (error != null)
{
// TODO: Show error message to user
}
elseif (code != null)
{
// Gotauthorizationcode, resolve OAuth tokens.          OAuthTaskis an AsyncTask
                  // tomakenetworkcalls(which must be off themainapplicationthread)
OAuthTasktask = newOAuthTask();
task.execute(new String[] { code });
}

    © 2010 Ping Identity Corporation
                                                                                      35
Native Mobile Client Integration
Getting a Token (cont’d)

•     Handling parameters – sample code (cont'd):

private class OAuthTask extends AsyncTask<String, String, String>
{       @Override
protected String doInBackground(String... params)
        {
                  String result = null;
try {
                  // param[0] = authorization code
JSONObjectjsonObject = getJSONFromTokenEndpoint(params[0]);


                  String accessToken = (String)jsonObject.get("access_token");
                  String refreshToken = (String)jsonObject.get("refresh_token");


                            // TODO: Use tokens
}
        catch (Exception e) { // Errorhandling, etc. }
}
    © 2010 Ping Identity Corporation
}                                                                                  36
© 2010 Ping Identity Corporation
Native Mobile Client Integration
Using a Token

•     Once an access_token is obtained, it can be used in the REST API call
      to the Resource Server.
•     "Bearer" tokens should be inserted into an HTTP Authorization header.
      They may also appear in the query string or request body.
•     Example REST API Request:




POST /msg/api HTTP/1.1
Host: rs.pingidentity.com
Authorization: Bearer PeRTSD9RQrbiuoaHVPxV41MzW1qS
Content-Type: application/x-www-form-urlencoded;charset=UTF-8


msg=This%20is%20a%20test%20message.%20%20Please%20respond.



    © 2010 Ping Identity Corporation
                                                                              38
Native Mobile Client Integration
Using a Token (cont'd)

•     Sample code:

// Form the Bearer token Authorization header
NSString*authzHeader = [NSStringstringWithFormat:@"Bearer %@", accessToken];


NSMutableURLRequest*request = [[[NSMutableURLRequestalloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"https://rs.idp.com/msg/api"]];
[request setValue:authzHeaderforHTTPHeaderField:@"Authorization"];


NSLog(@"Initiating URL connection to RS with access_token...");
NSURLConnection*conn=[[NSURLConnectionalloc] initWithRequest:requestdelegate:self];




    © 2010 Ping Identity Corporation
                                                                                      39
Native Mobile Client Integration
Using a Token (cont'd)

•      Sample code:

// Helper function to create HTTPS POST connections
HttpsURLConnectioncreateHttpsPostConnection(String urlString) throws IOException
{
    URL url = new URL(urlString);
URLConnectionurlConn = url.openConnection();
HttpsURLConnectionhttpsConn = (HttpsURLConnection) urlConn;


httpsConn.setRequestMethod("POST");
httpsConn.setDoOutput(true);
    return httpsConn;
}
// ... Making RS call:
{
HttpsURLConnectionhttpsConn = createHttpsPostConnection(RS_API_ENDPOINT);
httpsConn.setRequestProperty("Authorization", "Bearer " + accessToken);
OutputStreamWriterwriter = new OutputStreamWriter(httpsConn.getOutputStream());
writer.flush();
}    © 2010 Ping Identity Corporation
                                                                                   40
© 2010 Ping Identity Corporation
Native Mobile Client Integration
Refreshing a Token

•     The JSON structure returned by the token endpoint containing the
      access_tokenalso contains other useful parameters – namely:
       • expires_in – number of seconds before access_token can no
          longer be used.
       • refresh_token – can be stored persistently to request another
          access_token after expiry. Secure storage should be used (e.g.:
          iOS keychain).




{"token_type":"Bearer",
"expires_in":60,
"refresh_token":"uyAVrtyLZ2qPzI8rQ5UUTckCdGaJsz8XE8S58ecnt8",
"access_token":"PeRTSD9RQrbiuoaHVPxV41MzW1qS"}


    © 2010 Ping Identity Corporation
                                                                            42
Native Integration
Refreshing a Token (cont’d)
                                                 Ping specific:
•     To refresh an access token after expiry,   The partner OAuth client as
      use the refresh token to make a call to    defined in PingFederate must
      the token endpoint.                        have assigned (at a minimum)
                                                 the Refresh Grant Type.
                                                 Additional token mapping
•     Example Request:                           configuration is also required for
                                                 persistent grants.




POST /as/token.oauth2 HTTP/1.1
Host: as.pingidentity.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8


grant_type=refresh_token&refresh_token=qANLTbu17rk17lPszecHRi7rqJt46pG1qx0
nTAqXWH



    © 2010 Ping Identity Corporation
                                                                                      43
Native Client Integration
Refreshing a Token (cont’d)

•     The JSON response structure will contain an access token, expiry and type
      details – and depending on policy - a refresh token to replace the
      previously one sent.

•     Example JSON response structure:



{"token_type":"Bearer",
"expires_in":60,
"refresh_token":"5HmQjHHP6lGDDWxNh3tuwCzxtRjl95xYnVgvrfh5Kt",
"access_token":"sqhZPzxb7IAIa4kxdyLDJpxpgTFj"}


Ping Specific : The default policy in PingFederate is to roll the refresh token on each use. Once a
refresh token is returned in the response, the previously sent one is rendered invalid.



    © 2010 Ping Identity Corporation
                                                                                                      44
Other options
• Talk about RO Creds etc




© 2010 Ping Identity Corporation

Saas webinar-dec6-01

  • 1.
    So you're buildinga native app? (Or at least you should be) Paul Madsen Sr. Technical Architect © 2010 Ping Identity Corporation
  • 2.
    Agenda •Drivers •Very brief discussionof web vs native •Authentication for native apps •OAuth 2.0 •What does a client need to do to do OAuth? © 2010 Ping Identity Corporation
  • 3.
    © 2010 PingIdentity Corporation
  • 4.
    © 2010 PingIdentity Corporation
  • 5.
    © 2010 PingIdentity Corporation
  • 6.
    Mobile Application Models Web Applications Native Applications Web Server Web Server Mobile Web Page HTML JSON/XML Mobile Device Mobile Device Web App Native App Browser © 2010 Ping Identity Corporation
  • 7.
    Native Web © 2010Ping Identity Corporation
  • 8.
    Pros/cons © 2010 PingIdentity Corporation
  • 9.
    Native Applications Authentication Service Provider 1. User trades credentials for a token 2. Token delivered through the browser to native application 3. Native application Token Token presents token on API 1 4 calls Password 4. API endpoint returns 2 3 JSON/XML application data as Device JSON/XML Native Browser App © 2010 Ping Identity Corporation
  • 10.
    OAuth 2.0 – Anopen protocol to allow secure API authorization in a simple and standard method from desktop, mobile and web applications. – Defines authorization & authentication framework for RESTful APIs – Applied to delegated authorization – mitigates password anti- pattern - archetypical use case – Provides a standard way to give a ‘key’ to a third-party which allows only limited access to perform specific functions without divulging your credentials © 2010 Ping Identity Corporation
  • 11.
    Native Mobile OAuthOptions • DIY • Launching the browser (externally or embedded) • Detecting callback from the browser • JSON response parsing • Secure storage of persistent tokens • Use OAuth Client Library – Provides the above functionality with a higher level of abstraction. E.g.: • Google Toolbox for Mac - OAuth Controllers • http://code.google.com/p/gtm- oauth/wiki/GTMOAuthIntroduction • Google APIs Client Library for Java • http://code.google.com/p/google-api-java- client/downloads/detail?name=google-api-java-client- 1.4.1-beta.zip • (In Android) Android AccountManager © 2010 Ping Identity Corporation 11
  • 12.
    AccountManager •As of Android2.0, AccountManager manages accounts on device •Handles the OAuth 2.0 authorization flow on behalf of applications •Collects user consent (as opposed to via a browsert window) © 2010 Ping Identity Corporation
  • 13.
    Android OAuth options OAuth authz Device App Browser AS API call w token RS DIY & external browser Device Library OAuth authz App Browser AS API call w token RS Use OAuth library & embedded browser OAuth authz Device App Account AS Manager API call w token RS AccountManager © 2010 Ping Identity Corporation
  • 14.
    Detailed walk through • For completeness, we'll show the DIY model • We'll show what the native application needs to do to 1. Get user authenticated and get their authorization 2. Obtain an access token 3. Use that access token on an API call 4. Get a fresh access token when the original expires © 2010 Ping Identity Corporation
  • 15.
    © 2010 PingIdentity Corporation
  • 16.
    © 2010 PingIdentity Corporation
  • 17.
    Getting a tokenoverview 1. Open a browser and pass scopes 2. Deal with callback when it comes 3. Trade code for token © 2010 Ping Identity Corporation
  • 18.
    Native Mobile ClientIntegration Getting a Token • Identify when a user needs to grant access to something at the Resource Server • When this situation occurs, open a browser to: https://as.example.com/as/authorization.oauth2?c lient_id=<mobappclient_id>&response_type=code Pre-requisites: Note: Additional query parameters are possible: • The partner OAuth Client must be • scope – space delimited (URL encoded as %20) requested defined in PingFederate config. permissions of the client • Client must be assigned (at min.) the • state – an opaque value used by the partner to maintain state on Authorization Code grant type - callback and thus a defined callback URL. • idp – custom parameter to request SAML IdP based authentication • IdP Adapter Mappings to • pfidpadapterid – custom parameter to authenticate the user with a authenticate via an adapter named IdP Adapter © 2010 Ping Identity Corporation 18
  • 19.
    Native Mobile ClientIntegration Getting a Token (cont’d) • Open browser to authorization endpoint sample code: - (IBAction)doAction:(id)sender { NSLog(@"About to open Safari to Oauth AS Authorization Endpoint..."); // In this example, use a named IDP connection for user authentication NSString* launchUrl = @"https://as.pingidentity.com/as/authorization.oauth2?client_id=mobileclient1&respons e_type=code&idp=https://idp.acme.com/saml-entity-id"; [[UIApplicationsharedApplication] openURL:[NSURL URLWithString: launchUrl]]; } © 2010 Ping Identity Corporation 19
  • 20.
    Comparison of granttypes & models Authorization Code ( Resource Owner Embedded browser) Credentials • No need to leave app context • Password shared with 3rd party • Application owns login UI • Enables SSO • Enables strong authn • AS owns login UI • Visual trust cues (SSL lock) • Authentication can leverage stored passwords • Authentication can leverage existing sessions Authorization Code (Separate browser) © 2010 Ping Identity Corporation
  • 21.
    Authenticating the user •Talk about SSO options © 2010 Ping Identity Corporation
  • 22.
    © 2010 PingIdentity Corporation
  • 23.
    Native Mobile ClientIntegration Getting a Token (cont’d) • Authorization Page (default template): Requested Scope Partner Details © 2010 Ping Identity Corporation 23
  • 24.
    Native Mobile ClientIntegration Getting a Token (cont’d) • After the user authenticates and authorizes access at the Authorization Service, a callback (via HTTP redirect) will be made back to the Mobile Client Application. • Approaches for callback to the native application: • Use a custom registered URI scheme (e.g.: mobileapp://oauth-callback?code=xxxx). (Example follows) • Use a custom registered MIME-type. A redirect would send the browser to a HTTP endpoint that responds with that content-type HTTP header (e.g.: Content-type: application/mobileapp). © 2010 Ping Identity Corporation 24
  • 25.
    Native Mobile ClientIntegration Getting a Token (cont’d) • Registering a custom URI scheme in iOS: © 2010 Ping Identity Corporation 25
  • 26.
    Native Mobile ClientIntegration Getting a Token (cont’d) • Registering a custom URI scheme in Android: <activity android:name=".MyAppRegisterAccount" android:label="@string/addAccount" > <intent-filter> <action android:name="android.intent.action.VIEW"/> <category android:name="android.intent.category.DEFAULT"/> <category android:name="android.intent.category.BROWSABLE"/> <data android:scheme="mymobileapp" /> </intent-filter> </activity> © 2010 Ping Identity Corporation 26
  • 27.
    Native Mobile ClientIntegration Getting a Token (cont’d) • Receiving callback – sample code: - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { // Schema based application call. NSLog(@"Schema based call received. URL: %@", url); NSLog(@"Parsing query string..."); NSMutableDictionary *qsParms = [[NSMutableDictionaryalloc] init]; for (NSString *param in [[url query] componentsSeparatedByString:@"&"]) { NSArray *elts = [paramcomponentsSeparatedByString:@"="]; if([elts count] < 2) continue; [qsParmssetObject:[elts objectAtIndex:1] forKey:[elts objectAtIndex:0]]; }; // Process received URL parameters (code, error, etc.)... © 2010 Ping Identity Corporation 27
  • 28.
    Native Mobile ClientIntegration Getting a Token (cont’d) • Receiving callback – sample code: @Override public void onCreate(Bundle savedInstanceState) { // Could also be inside onNewInstance depending on the launchMode type super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent intent = getIntent(); Uri uri = intent.getData(); if (uri != null) { // Callback from browser link / redirection // Process received URL parameters (code, error, etc.)... } © 2010 Ping Identity Corporation 28
  • 29.
    Native Mobile ClientIntegration Getting a Token (cont’d) • The following parameters are possible on the callback: • code – the authorization code to resolve the OAuth token • error – an error code (e.g.: access_denied) • error_description– descriptive text about the error • state – the same state value given in the original redirection • Callback processing: • The code callback parameter must be subsequentlyresolved into OAuth tokens by making a REST API call to the Authorization Server token endpoint . • If error is present in the callback, the application should gracefully fail and present a meaningful error to the user (possibly leveraging error_description). © 2010 Ping Identity Corporation 29
  • 30.
    Native Mobile ClientIntegration Getting a Token (cont’d) • Example token endpoint Request: POST /as/token.oauth2 HTTP/1.1 Host: as.example.com Content-Type: application/x-www-form-urlencoded;charset=UTF-8 grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA © 2010 Ping Identity Corporation 30
  • 31.
    Native Mobile ClientIntegration Getting a Token (cont’d) • Example token endpoint Response: HTTP/1.1 200 OK Content-Type: application/json;charset=UTF-8 Cache-Control: no-store Pragma: no-cache {"token_type":"Bearer","expires_in":60,"refresh_token":"uyAVrtyLZ2qPzI8rQ5 UUTckCdGaJsz8XE8S58ecnt8","access_token":"PeRTSD9RQrbiuoaHVPxV41MzW1qS"} © 2010 Ping Identity Corporation 31
  • 32.
    Native Mobile ClientIntegration Getting a Token (cont’d) • Handling parameters – sample code: // Parse of URL query string complete if (error != nil) { // TODO: Show error message to user } else { NSString *code = [qsParmsobjectForKey:@"code"]; // Form HTTP POST to resolve JSON structure NSString*post = [NSStringstringWithFormat:@"grant_type=authorization_code&code=%@", code]; NSData*postData = [post dataUsingEncoding:NSASCIIStringEncodingallowLossyConversion:YES]; © 2010 Ping Identity Corporation 32
  • 33.
    Native Mobile ClientIntegration Getting a Token (cont’d) • Handling parameters – sample code (cont'd): NSString*postLength = [NSStringstringWithFormat:@"%d", [postDatalength]]; NSMutableURLRequest *request = [[[NSMutableURLRequestalloc] init] autorelease]; [requestsetURL:[NSURL URLWithString:@"https://as.idp.com/as/token.oauth2"]]; [requestsetHTTPMethod:@"POST"]; [requestsetValue:postLengthforHTTPHeaderField:@"Content-Length"]; [requestsetValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [requestsetHTTPBody:postData]; NSURLConnection *conn=[[NSURLConnectionalloc] initWithRequest:requestdelegate:self]; if (conn) { receivedData = [[NSMutableData data] retain]; } } © 2010 Ping Identity Corporation 33
  • 34.
    Native Mobile ClientIntegration Getting a Token (cont’d) • Handling parameters – sample code (cont'd): - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // json-framework library: https://github.com/stig/json-framework/ SBJsonParser*jsonParser = [[SBJsonParseralloc] init]; NSString*aStr = [[NSStringalloc] initWithData:receivedDataencoding:NSASCIIStringEncoding]; NSString*accessToken = nil; NSString*refreshToken = nil; id object = [jsonParserobjectWithString:aStr]; if (object) { NSLog(@"JSON parsed successfully."); if ([object isKindOfClass:[NSDictionary class]]) { NSDictionary *nsDict = (NSDictionary*)object; accessToken = [nsDictobjectForKey:@"access_token"]; refreshToken = [nsDictobjectForKey:@"refresh_token"]; } © 2010 Ping Identity Corporation 34
  • 35.
    Native Mobile ClientIntegration Getting a Token (cont’d) • Handling parameters – sample code: // Callback from browser link / redirection String code = uri.getQueryParameter("code"); String error = uri.getQueryParameter("error"); if (error != null) { // TODO: Show error message to user } elseif (code != null) { // Gotauthorizationcode, resolve OAuth tokens. OAuthTaskis an AsyncTask // tomakenetworkcalls(which must be off themainapplicationthread) OAuthTasktask = newOAuthTask(); task.execute(new String[] { code }); } © 2010 Ping Identity Corporation 35
  • 36.
    Native Mobile ClientIntegration Getting a Token (cont’d) • Handling parameters – sample code (cont'd): private class OAuthTask extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... params) { String result = null; try { // param[0] = authorization code JSONObjectjsonObject = getJSONFromTokenEndpoint(params[0]); String accessToken = (String)jsonObject.get("access_token"); String refreshToken = (String)jsonObject.get("refresh_token"); // TODO: Use tokens } catch (Exception e) { // Errorhandling, etc. } } © 2010 Ping Identity Corporation } 36
  • 37.
    © 2010 PingIdentity Corporation
  • 38.
    Native Mobile ClientIntegration Using a Token • Once an access_token is obtained, it can be used in the REST API call to the Resource Server. • "Bearer" tokens should be inserted into an HTTP Authorization header. They may also appear in the query string or request body. • Example REST API Request: POST /msg/api HTTP/1.1 Host: rs.pingidentity.com Authorization: Bearer PeRTSD9RQrbiuoaHVPxV41MzW1qS Content-Type: application/x-www-form-urlencoded;charset=UTF-8 msg=This%20is%20a%20test%20message.%20%20Please%20respond. © 2010 Ping Identity Corporation 38
  • 39.
    Native Mobile ClientIntegration Using a Token (cont'd) • Sample code: // Form the Bearer token Authorization header NSString*authzHeader = [NSStringstringWithFormat:@"Bearer %@", accessToken]; NSMutableURLRequest*request = [[[NSMutableURLRequestalloc] init] autorelease]; [request setURL:[NSURL URLWithString:@"https://rs.idp.com/msg/api"]]; [request setValue:authzHeaderforHTTPHeaderField:@"Authorization"]; NSLog(@"Initiating URL connection to RS with access_token..."); NSURLConnection*conn=[[NSURLConnectionalloc] initWithRequest:requestdelegate:self]; © 2010 Ping Identity Corporation 39
  • 40.
    Native Mobile ClientIntegration Using a Token (cont'd) • Sample code: // Helper function to create HTTPS POST connections HttpsURLConnectioncreateHttpsPostConnection(String urlString) throws IOException { URL url = new URL(urlString); URLConnectionurlConn = url.openConnection(); HttpsURLConnectionhttpsConn = (HttpsURLConnection) urlConn; httpsConn.setRequestMethod("POST"); httpsConn.setDoOutput(true); return httpsConn; } // ... Making RS call: { HttpsURLConnectionhttpsConn = createHttpsPostConnection(RS_API_ENDPOINT); httpsConn.setRequestProperty("Authorization", "Bearer " + accessToken); OutputStreamWriterwriter = new OutputStreamWriter(httpsConn.getOutputStream()); writer.flush(); } © 2010 Ping Identity Corporation 40
  • 41.
    © 2010 PingIdentity Corporation
  • 42.
    Native Mobile ClientIntegration Refreshing a Token • The JSON structure returned by the token endpoint containing the access_tokenalso contains other useful parameters – namely: • expires_in – number of seconds before access_token can no longer be used. • refresh_token – can be stored persistently to request another access_token after expiry. Secure storage should be used (e.g.: iOS keychain). {"token_type":"Bearer", "expires_in":60, "refresh_token":"uyAVrtyLZ2qPzI8rQ5UUTckCdGaJsz8XE8S58ecnt8", "access_token":"PeRTSD9RQrbiuoaHVPxV41MzW1qS"} © 2010 Ping Identity Corporation 42
  • 43.
    Native Integration Refreshing aToken (cont’d) Ping specific: • To refresh an access token after expiry, The partner OAuth client as use the refresh token to make a call to defined in PingFederate must the token endpoint. have assigned (at a minimum) the Refresh Grant Type. Additional token mapping • Example Request: configuration is also required for persistent grants. POST /as/token.oauth2 HTTP/1.1 Host: as.pingidentity.com Content-Type: application/x-www-form-urlencoded;charset=UTF-8 grant_type=refresh_token&refresh_token=qANLTbu17rk17lPszecHRi7rqJt46pG1qx0 nTAqXWH © 2010 Ping Identity Corporation 43
  • 44.
    Native Client Integration Refreshinga Token (cont’d) • The JSON response structure will contain an access token, expiry and type details – and depending on policy - a refresh token to replace the previously one sent. • Example JSON response structure: {"token_type":"Bearer", "expires_in":60, "refresh_token":"5HmQjHHP6lGDDWxNh3tuwCzxtRjl95xYnVgvrfh5Kt", "access_token":"sqhZPzxb7IAIa4kxdyLDJpxpgTFj"} Ping Specific : The default policy in PingFederate is to roll the refresh token on each use. Once a refresh token is returned in the response, the previously sent one is rendered invalid. © 2010 Ping Identity Corporation 44
  • 45.
    Other options • Talkabout RO Creds etc © 2010 Ping Identity Corporation

Editor's Notes

  • #4 Consumerization of IT, BYOD
  • #6 Appplication Markets
  • #10 Native applications authenticate to REST APIs by presenting a tokenThe precursor act of the native application obtaining a token is often called ‘authorization’ (particularly in those cases when the API fronts user info, eg profile, tweets, etc)User authorizes (or consents) to the native application having access to the API (and their data) – the authorization is manifested as the issuance of a token to the API clientOAuth 2.0 is default protocol by which a Client obtains the desired authorizations and the corresponding token