Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Saas webinar-dec6-01


Published on

Published in: Technology
  • Be the first to comment

Saas webinar-dec6-01

  1. 1. So youre building a native app? (Or at least you should be) Paul Madsen Sr. Technical Architect© 2010 Ping Identity Corporation
  2. 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. 3. © 2010 Ping Identity Corporation
  4. 4. © 2010 Ping Identity Corporation
  5. 5. © 2010 Ping Identity Corporation
  6. 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. 7. NativeWeb © 2010 Ping Identity Corporation
  8. 8. Pros/cons© 2010 Ping Identity Corporation
  9. 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 asDevice JSON/XML Native Browser App © 2010 Ping Identity Corporation
  10. 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. 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 • oauth/wiki/GTMOAuthIntroduction • Google APIs Client Library for Java • client/downloads/detail?name=google-api-java-client-• (In Android) Android AccountManager © 2010 Ping Identity Corporation 11
  12. 12. AccountManager•As of Android 2.0,AccountManagermanages accounts ondevice•Handles the OAuth 2.0authorization flow onbehalf of applications•Collects user consent(as opposed to via abrowsert window) © 2010 Ping Identity Corporation
  13. 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. 14. Detailed walk through• For completeness, well show the DIY model• Well 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. 15. © 2010 Ping Identity Corporation
  16. 16. © 2010 Ping Identity Corporation
  17. 17. Getting a token overview1. Open a browser and pass scopes2. Deal with callback when it comes3. Trade code for token© 2010 Ping Identity Corporation
  18. 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: lient_id=<mobappclient_id>&response_type=codePre-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. 19. Native Mobile Client IntegrationGetting 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 authenticationNSString* launchUrl =@""; [[UIApplicationsharedApplication] openURL:[NSURL URLWithString: launchUrl]];} © 2010 Ping Identity Corporation 19
  20. 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. 21. Authenticating the user• Talk about SSO options© 2010 Ping Identity Corporation
  22. 22. © 2010 Ping Identity Corporation
  23. 23. Native Mobile Client IntegrationGetting a Token (cont’d)• Authorization Page (default template): Requested Scope Partner Details © 2010 Ping Identity Corporation 23
  24. 24. Native Mobile Client IntegrationGetting 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. 25. Native Mobile Client IntegrationGetting a Token (cont’d)• Registering a custom URI scheme in iOS: © 2010 Ping Identity Corporation 25
  26. 26. Native Mobile Client IntegrationGetting 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. 27. Native Mobile Client IntegrationGetting 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. 28. Native Mobile Client IntegrationGetting a Token (cont’d)• Receiving callback – sample code:@Overridepublic void onCreate(Bundle savedInstanceState){// Could also be inside onNewInstance depending on the launchMode typesuper.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. 29. Native Mobile Client IntegrationGetting 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. 30. Native Mobile Client IntegrationGetting a Token (cont’d)• Example token endpoint Request:POST /as/token.oauth2 HTTP/1.1Host: as.example.comContent-Type: application/x-www-form-urlencoded;charset=UTF-8grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA © 2010 Ping Identity Corporation 30
  31. 31. Native Mobile Client IntegrationGetting a Token (cont’d)• Example token endpoint Response:HTTP/1.1 200 OKContent-Type: application/json;charset=UTF-8Cache-Control: no-storePragma: no-cache{"token_type":"Bearer","expires_in":60,"refresh_token":"uyAVrtyLZ2qPzI8rQ5UUTckCdGaJsz8XE8S58ecnt8","access_token":"PeRTSD9RQrbiuoaHVPxV41MzW1qS"} © 2010 Ping Identity Corporation 31
  32. 32. Native Mobile Client IntegrationGetting 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 structureNSString*post = [NSStringstringWithFormat:@"grant_type=authorization_code&code=%@",code];NSData*postData = [postdataUsingEncoding:NSASCIIStringEncodingallowLossyConversion:YES]; © 2010 Ping Identity Corporation 32
  33. 33. Native Mobile Client IntegrationGetting a Token (cont’d)• Handling parameters – sample code (contd):NSString*postLength = [NSStringstringWithFormat:@"%d", [postDatalength]];NSMutableURLRequest *request = [[[NSMutableURLRequestalloc] init] autorelease]; [requestsetURL:[NSURL URLWithString:@""]]; [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. 34. Native Mobile Client IntegrationGetting a Token (cont’d)• Handling parameters – sample code (contd):- (void)connectionDidFinishLoading:(NSURLConnection *)connection { // json-framework library:*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. 35. Native Mobile Client IntegrationGetting a Token (cont’d)• Handling parameters – sample code: // Callback from browser link / redirectionString 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. 36. Native Mobile Client IntegrationGetting a Token (cont’d)• Handling parameters – sample code (contd):private class OAuthTask extends AsyncTask<String, String, String>{ @Overrideprotected String doInBackground(String... params) { String result = null;try { // param[0] = authorization codeJSONObjectjsonObject = 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. 37. © 2010 Ping Identity Corporation
  38. 38. Native Mobile Client IntegrationUsing 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.1Host: rs.pingidentity.comAuthorization: Bearer PeRTSD9RQrbiuoaHVPxV41MzW1qSContent-Type: application/x-www-form-urlencoded;charset=UTF-8msg=This%20is%20a%20test%20message.%20%20Please%20respond. © 2010 Ping Identity Corporation 38
  39. 39. Native Mobile Client IntegrationUsing a Token (contd)• Sample code:// Form the Bearer token Authorization headerNSString*authzHeader = [NSStringstringWithFormat:@"Bearer %@", accessToken];NSMutableURLRequest*request = [[[NSMutableURLRequestalloc] init] autorelease];[request setURL:[NSURL URLWithString:@""]];[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. 40. Native Mobile Client IntegrationUsing a Token (contd)• Sample code:// Helper function to create HTTPS POST connectionsHttpsURLConnectioncreateHttpsPostConnection(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. 41. © 2010 Ping Identity Corporation
  42. 42. Native Mobile Client IntegrationRefreshing 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. 43. Native IntegrationRefreshing 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.1Host: as.pingidentity.comContent-Type: application/x-www-form-urlencoded;charset=UTF-8grant_type=refresh_token&refresh_token=qANLTbu17rk17lPszecHRi7rqJt46pG1qx0nTAqXWH © 2010 Ping Identity Corporation 43
  44. 44. Native Client IntegrationRefreshing 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 arefresh token is returned in the response, the previously sent one is rendered invalid. © 2010 Ping Identity Corporation 44
  45. 45. Other options• Talk about RO Creds etc© 2010 Ping Identity Corporation