SlideShare a Scribd company logo
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

More Related Content

PPTX
Mobile Native OAuth Decision Framework
PPTX
Protecting Online Identities
PPTX
Protecting Online Identities - MIX09
PPTX
API Management and Mobile App Enablement
PDF
CIS13: Introduction to OAuth 2.0
PDF
Gluecon oauth-03
PPTX
Thomas vochten claims-spsbe26
PPTX
Authentication Server
Mobile Native OAuth Decision Framework
Protecting Online Identities
Protecting Online Identities - MIX09
API Management and Mobile App Enablement
CIS13: Introduction to OAuth 2.0
Gluecon oauth-03
Thomas vochten claims-spsbe26
Authentication Server

What's hot (17)

PPTX
OAuth 2.0 and Mobile Devices: Is that a token in your phone in your pocket or...
PPTX
Workshop: Advanced Federation Use-Cases with PingFederate
PDF
OAuth big picture
PDF
Saml
PPTX
ACDKOCHI19 - Enterprise grade security for web and mobile applications on AWS
PPTX
OAuth2 & OpenID Connect
PDF
Office 365: Planning and Automating for Hybrid Identity Scenarios in the Clou...
PDF
Cybercom Enhanced Security Platform, CESP-ID
PDF
CIS13: Identity as a Matter of Public Safety: A Case Study in Secure API Acce...
PPTX
Why Assertion-based Access Token is preferred to Handle-based one?
PDF
OAuth 2.0 and OpenID Connect
PDF
OAuth 2.0 #idit2012
PDF
SharePoint Saturday The Conference 2011 - Extranets & Claims Authentication
PPT
Slide 1 - Authenticated Reseller SSL Certificate Authority
PPTX
Using & Abusing APIs: An Examination of the API Attack Surface
PDF
Oauth Nightmares Abstract OAuth Nightmares
PPT
OAuth 2.0 and Mobile Devices: Is that a token in your phone in your pocket or...
Workshop: Advanced Federation Use-Cases with PingFederate
OAuth big picture
Saml
ACDKOCHI19 - Enterprise grade security for web and mobile applications on AWS
OAuth2 & OpenID Connect
Office 365: Planning and Automating for Hybrid Identity Scenarios in the Clou...
Cybercom Enhanced Security Platform, CESP-ID
CIS13: Identity as a Matter of Public Safety: A Case Study in Secure API Acce...
Why Assertion-based Access Token is preferred to Handle-based one?
OAuth 2.0 and OpenID Connect
OAuth 2.0 #idit2012
SharePoint Saturday The Conference 2011 - Extranets & Claims Authentication
Slide 1 - Authenticated Reseller SSL Certificate Authority
Using & Abusing APIs: An Examination of the API Attack Surface
Oauth Nightmares Abstract OAuth Nightmares
Ad

Viewers also liked (8)

PDF
Using Social Software to Market yourself - inside and outside the firewall
PPT
Enterprise 2.0 Social Networking In Ibm 20091026 Final
PPT
DIWD Concordia
PPT
Searching the Now
PPT
Micro Blogging In The Enterprise Final
PPTX
Native application Single SignOn
PDF
Innovation antwerp45
PDF
Public v -_ibm_social_software_story_-_soc_med_for_ce_os_sept2011
Using Social Software to Market yourself - inside and outside the firewall
Enterprise 2.0 Social Networking In Ibm 20091026 Final
DIWD Concordia
Searching the Now
Micro Blogging In The Enterprise Final
Native application Single SignOn
Innovation antwerp45
Public v -_ibm_social_software_story_-_soc_med_for_ce_os_sept2011
Ad

Similar to Saas webinar-dec6-01 (20)

PPTX
CIS 2012 - Going Mobile with PingFederate and OAuth 2
PPTX
Single sign-on Across Mobile Applications from RSAConference
PPTX
Smartphone Native Application OP
PDF
AdWords API and OAuth 2.0
PPTX
OAuth - Don’t Throw the Baby Out with the Bathwater
PDF
OAuth 1.0
PDF
OAuth: Trust Issues
PDF
OAuth 2.0
PDF
OAuth2 on Ericsson Labs
PDF
Nordic APIs - Building a Secure API
PDF
OAuth for your API - The Big Picture
PDF
Implementing OAuth
PDF
Implementing OAuth with PHP
PDF
Oauth Php App
PPTX
Enterprise Access Control Patterns for REST and Web APIs Gluecon 2011, Franco...
PPTX
Enterprise Access Control Patterns for Rest and Web APIs
PDF
Petr Dvořák: Mobilní webové služby pohledem iPhone developera
PDF
- Webexpo 2010
PDF
Draft Ietf Oauth V2 12
PPTX
Esquema de pasos de ejecución IdM
CIS 2012 - Going Mobile with PingFederate and OAuth 2
Single sign-on Across Mobile Applications from RSAConference
Smartphone Native Application OP
AdWords API and OAuth 2.0
OAuth - Don’t Throw the Baby Out with the Bathwater
OAuth 1.0
OAuth: Trust Issues
OAuth 2.0
OAuth2 on Ericsson Labs
Nordic APIs - Building a Secure API
OAuth for your API - The Big Picture
Implementing OAuth
Implementing OAuth with PHP
Oauth Php App
Enterprise Access Control Patterns for REST and Web APIs Gluecon 2011, Franco...
Enterprise Access Control Patterns for Rest and Web APIs
Petr Dvořák: Mobilní webové služby pohledem iPhone developera
- Webexpo 2010
Draft Ietf Oauth V2 12
Esquema de pasos de ejecución IdM

More from Paul Madsen (8)

PPTX
Onboarding in the IoT
PPTX
BYOD - it's an identity thing
PPTX
Madsen byod-csa-02
PPTX
A recipe for standards-based Cloud IdM
PPTX
Jan19 scim webinar-04
PPT
Proxying Assurance between OpenID & SAML
PPT
Oauth 01
PDF
Iiw2007b Madsen 01
Onboarding in the IoT
BYOD - it's an identity thing
Madsen byod-csa-02
A recipe for standards-based Cloud IdM
Jan19 scim webinar-04
Proxying Assurance between OpenID & SAML
Oauth 01
Iiw2007b Madsen 01

Recently uploaded (20)

PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
ai-archetype-understanding-the-personality-of-agentic-ai.pdf
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
PDF
Reimagining Insurance: Connected Data for Confident Decisions.pdf
PDF
Sensors and Actuators in IoT Systems using pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
Belt and Road Supply Chain Finance Blockchain Solution
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Event Presentation Google Cloud Next Extended 2025
PPTX
CroxyProxy Instagram Access id login.pptx
PDF
Smarter Business Operations Powered by IoT Remote Monitoring
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PDF
KodekX | Application Modernization Development
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
ai-archetype-understanding-the-personality-of-agentic-ai.pdf
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Reimagining Insurance: Connected Data for Confident Decisions.pdf
Sensors and Actuators in IoT Systems using pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Understanding_Digital_Forensics_Presentation.pptx
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Belt and Road Supply Chain Finance Blockchain Solution
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Event Presentation Google Cloud Next Extended 2025
CroxyProxy Instagram Access id login.pptx
Smarter Business Operations Powered by IoT Remote Monitoring
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
KodekX | Application Modernization Development
NewMind AI Monthly Chronicles - July 2025
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf

Saas webinar-dec6-01

  • 1. So you're building a native app? (Or at least you should be) Paul Madsen Sr. Technical Architect © 2010 Ping Identity Corporation
  • 2. 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
  • 3. © 2010 Ping Identity Corporation
  • 4. © 2010 Ping Identity Corporation
  • 5. © 2010 Ping Identity 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 © 2010 Ping Identity Corporation
  • 8. Pros/cons © 2010 Ping Identity 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 – 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
  • 11. 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
  • 12. 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
  • 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 Ping Identity Corporation
  • 16. © 2010 Ping Identity Corporation
  • 17. 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
  • 18. 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
  • 19. 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
  • 20. 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
  • 21. Authenticating the user • Talk about SSO options © 2010 Ping Identity Corporation
  • 22. © 2010 Ping Identity Corporation
  • 23. Native Mobile Client Integration Getting a Token (cont’d) • Authorization Page (default template): Requested Scope Partner Details © 2010 Ping Identity Corporation 23
  • 24. 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
  • 25. Native Mobile Client Integration Getting a Token (cont’d) • Registering a custom URI scheme in iOS: © 2010 Ping Identity Corporation 25
  • 26. 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
  • 27. 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
  • 28. 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
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. 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
  • 35. 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
  • 36. 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
  • 37. © 2010 Ping Identity Corporation
  • 38. 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
  • 39. 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
  • 40. 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
  • 41. © 2010 Ping Identity Corporation
  • 42. 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
  • 43. 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
  • 44. 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
  • 45. Other options • Talk about 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