Making Connections with Spring Social


Published on

Speaker: Craig Walls
The modern web is rich with APIs that can be consumed by other applications, enabling an integrated experience for the users who hold accounts on the websites that front those APIs. Many of these APIs are secured with OAuth, an authorization specification for securing REST APIs. Spring Social is an extension to the Spring Framework that enables Spring applications to establish connections with those APIs on behalf of their users with little or no need to muck about in the intricacies of OAuth.
In this session, we'll explore how Spring Social brings API connectivity to Spring applications. We'll also uncover the newest features of Spring Social that make it easier than ever to link your application's users to the identities they maintain on various sites across the web.

Published in: Technology

Making Connections with Spring Social

  1. 1. Making Connections with Spring Social Craig Walls, Spring Social Project Lead @habuma / @SpringSocial © 2013 SpringOne 2GX. All rights reserved. Do not distribute without permission.
  2. 2. A Web of APIs REST/Lightweight APIs are everywhere The gateway to user-owned data Presents technical opportunity to plug into your users’ social and data graph Inject and ingest data Drive decisions, marketing, experience, etc 2
  3. 3. The Modern Web is Social Facebook : 1.15 billion users Twitter: Over 500 million total users 200 million active users LinkedIn: 238 million users Google+: 343 million active users Source: 3
  4. 4. Not Just Social... Evernote : 65 million users Dropbox: 200 million users GitHub: 3.5 million users Quickbooks Online Source: 4
  5. 5. And LOTS more... 500px Basecamp/37Signals Bebo Bitbucket Crowdtilt CrunchBase Digg Dropbox E*Trade Etsy Flattr Flickr Formstack 5 Foursquare Friendster GeekList GetGlue Geoloqi Gliffy Google (not just G+) HootSuite Instagram Instapaper Khan Academy Klout Lockerz MapMyFitness Meetup MerchantCircle Miso Mixcloud Nk OpenID OpenTable Pastebin Photobucket Pinterest Plurk Posterous Rotten Tomatoes Salesforce Chatter SlideShare SmugMug SoundCoud Springpad StatusNet StumbleUpon TripIt Tumblr UrbanAirship Veevop Viadeo Vimeo Vkontakte Weibo Windows Live Xero Yahoo! Yammer Yelp YouTube ...and more...
  6. 6. Serious Fun 50% of technology companies have acquired a customer through Twitter Source: 70% of business-to-consumer marketers have acquired a customer through Facebook Source: The Obama 2012 campaign leveraged social networks as a source of “big data” to win votes Source: 6
  7. 7. Social Opportunities Nearly 4 in 5 active internet users visit social networks Opportunities Build/reenforce brand loyalty Listen for and react to customer opinion Drive qualified traffic to your site/product Enhance user experience 7
  8. 8. API Example: Fetching a Facebook Profile 8
  9. 9. API Example: Fetching Facebook Friends 9
  10. 10. API Example: Posting a Tweet Using Spring’s RestTemplate: RestTemplate rest = new RestTemplate(); MultiValueMap<String, Object> tweetParams = new LinkedMultiValueMap<String, Object>(); tweetParams.add("status", "Hello from #s2gx !"); rest.postForObject("", ! ! tweetParams, String.class); Oh no! WARNING: POST request for "" resulted in 401 (Unauthorized); invoking error handler org.springframework.web.client.HttpClientErrorException: 401 Unauthorized ! at org.springframework.web.client.DefaultResponseErrorHandler.handleError( ! at org.springframework.web.client.RestTemplate.handleResponseError( ! at org.springframework.web.client.RestTemplate.doExecute( ! at org.springframework.web.client.RestTemplate.execute( ! at org.springframework.web.client.RestTemplate.postForObject( 10
  11. 11. Web APIs and Security
  12. 12. API Security Styles Traditional Security Consumer/Provider Consumer authenticates with provider Provider makes security decisions Individual Security Client/Provider/Owner Client and Owner authenticate with Provider Owner makes security decisions Client is granted or denied access 12
  13. 13. OAuth Open standard for API authorization The user is the security administrator Decides if an app gets access Decides the scope of the access Three versions of OAuth OAuth 1.0 OAuth 1.0a OAuth 2 13
  14. 14. Authentication-Centric REST Security A User 14 An Application An API holding the user’s data that the application wants to access
  15. 15. User-Administered Authorization 15
  16. 16. The OAuth 1 “Dance” A. Request an unauthorized request token B. Request token returned to consumer C. Redirect user to provider for authorization D. Authorization verifier returned to consumer (OAuth 1.0a) E. Exchange request token/verifier for access token F. Access token and secret returned to consumer G. Sign requests using access token to access API endpoints 16
  17. 17. Signing Requests for OAuth 1 Create a base string Encode all query/form parameters Sort all query/form parameters Concatenate them, separated with “&” HTTP Method + “&” + URL + “&” + sorted/encoded parameters Encrypt the base string to create a signature HMAC-SHA1 is common Spec also allows for PLAINTEXT and RSA-SHA1 Add Authorization header to the API request 17
  18. 18. Simpler OAuth with OAuth 2 No concept of request token HTTPS for encryption No signature or canonicalization of request Simple Authorization header Multiple grant types Authorization Code, Implicit, Password, Client Credentials Scoped authorization Short-lived tokens, long-lived authorization Not final...currently at draft 31 18
  19. 19. OAuth 2 Authorization Code Grant Similar to OAuth 1.0a flow Start with redirect to provider After authorization, redirect back to client with authorization code Code is exchanged for access token Client must keep tokens confidential Appropriate for server-side of a web application 19
  20. 20. OAuth 2 Authorization Header (Bearer Token) Much simpler than OAuth 1.0/1.0a Authorization: Bearer e139a950-2fc5-4822-9266-8a2b572108c5 Differs across different drafts of OAuth 2 Authorization: BEARER e139a950-2fc5-4822-9266-8a2b572108c5 Authorization: OAuth e139a950-2fc5-4822-9266-8a2b572108c5 Authorization: Token token=“e139a950-2fc5-4822-9266-8a2b572108c5” Can optionally be sent via access_token parameter 20
  21. 21. OAuth 2 Authorization Header (MAC Token) Not as simple as Bearer Token Not quite (but almost) as complex as OAuth 1.0/1.0a More secure than Bearer Token Authorization: MAC id="h480djs93dh8", ts="1336363200", nonce="dj83hs9s", mac="bhCQXTVyfj5cmA9uKkPFx1zeOXM=" id: the MAC key identifier (e.g., the app ID) ts: a timestamp nonce: a unique string generated by the client mac: the HTTP request message authentication code (e.g., the signature) 21
  22. 22. API Example: Facebook Profile Revisited 22
  23. 23. API Client Challenges 1. Must obtain authorization 2. Must securely store tokens 3. Must generate Authorization header 4. Must (un)marshal data received from/sent to API 5. Must handle errors from API 6. Must renew tokens if expired or revoked 23
  24. 24. Introducing Spring Social
  25. 25. Introducing Spring Social Extension to Spring Framework that allows you to connect with SaaS providers Key Features An extensible connection framework API bindings Sign-in-with-Provider Support @SpringSocial 25
  26. 26. Spring Social Project Family Core Connection Framework, Web-Level Features, Security Provider Extensions Facebook, Twitter, LinkedIn, GitHub, TripIt Community Extensions 500px, Alfresco,, BitBucket, Daum, Digg, Dropbox, Flattr, Flickr, Foursquare, GeekList, Google, Instagram, Intuit (QBO), Khan Academy,, Miso, Mixcloud, Nk, Salesforce, SoundCloud, Tumblr, Viadeo, Vkontakte, Weibo, Xing, Yammer SpringSocial.NET Spring for Android Android-ready RestTemplate and Spring Social support 26
  27. 27. Spring Social’s Key Components ConnectController Connection Factories/Connection Factory Locator Connection Repository API Bindings 27
  28. 28. Spring Social’s Sign-In Components ProviderSignInController SocialAuthenticationFilter CanvasSignInController 28
  29. 29. Steps to Connecting with Spring Social Obtain application credentials from API provider Configure Provider Configure ConnectController Configure UserIdSource 29
  30. 30. Obtain application credentials (Facebook) 30
  31. 31. Obtain application credentials (Twitter) 31
  32. 32. Configuring Spring Social @Configuration @EnableJdbcConnectionRepository @EnableFacebook(appId="${facebook.clientId}", appSecret="${facebook.clientSecret}") public class SocialConfig { @Bean public ConnectController connectController( ConnectionFactoryLocator connectionFactoryLocator, ConnectionRepository connectionRepository) { return ConnectController(connectionFactoryLocator, connectionRepository); } @Bean public UserIdSource userIdSource() { return new AuthenticationNameUserIdSource(); } } 32
  33. 33. Configuring Spring Social with XML <context:property-placeholder location= "classpath:/org/springframework/social/showcase/config/" /> <facebook:config app-id="${facebook.clientId}" app-secret="${facebook.clientSecret}" app-namespace="socialshowcase" /> <social:jdbc-connection-repository/>! <bean id="userIdSource" class="" /> <bean id="connectController" class="" autowire="constructor" /> 33
  34. 34. Injecting and Using API Bindings @Controller public class TwitterTimelineController { ! ! ! ! ! ! private final Twitter twitter; ! ! ! ! ! @RequestMapping(value="/twitter/tweet", method=RequestMethod.POST) public String postTweet(String message) { ! twitter.timelineOperations().updateStatus(message); ! return "redirect:/twitter"; } } 34 @Inject public TwitterTimelineController(Twitter twitter) { ! this.twitter = twitter; }
  35. 35. ConnectController Endpoints GET /connect Display connection status for all providers GET /connect/{provider} Display connection status for a specific provider POST /connect/{provider} Initiate connection flow for the specified provider GET /connect/{provider}?oauth_token={t}[&verifier={v}] Handle callback for OAuth 1.0/1.0a provider GET /connect/{provider}?code={c} Handle callback for OAuth 2 provider DELETE /connect/{provider} Remove all connections for a given provider DELETE /connect/{provider}/{provider user ID} Remove a single connection for a given provider, identified by the user’s user ID at the provider 35
  36. 36. Sign-in-with-Provider Two Options ProviderSignInController Security mechanism agnostic Best choice when not using Spring Security SocialAuthenticationFilter Tighter integration with Spring Security. Best choice when using Spring Security 36
  37. 37. ProviderSignInController Similar flow as ConnectController/Different Goal Compares connections (by user ID) If there’s a match, user is signed in If no match, then user is sent to signup page @Bean public ProviderSignInController providerSignInController( ConnectionFactoryLocator connectionFactoryLocator, UsersConnectionRepository usersConnectionRepository, RequestCache requestCache) { return new ProviderSignInController(connectionFactoryLocator, usersConnectionRepository, new SimpleSignInAdapter(requestCache)); } 37
  38. 38. ProviderSignInController Endpoints POST /signin/{provider} Initiate signin flow for the specified provider GET /signin/{provider}?oauth_token={t}[&verifier={v}] Handle callback for OAuth 1.0/1.0a provider. Compare GET /signin/{provider}?code={c} Handle callback from OAuth 2 provider GET /signin/{provider}?error={e} Handle callback from OAuth 2 provider indicating an authorization error 38
  39. 39. SocialAuthenticationFilter A real Spring Security Authentication Filter Follows roughly the same flow as ProviderSignInController Plugs into Spring Security filter chain like any other authentication filter Comes with a configurer for Spring Security 3.2 configuration protected void configure(HttpSecurity http) throws Exception { http .formLogin() .loginPage("/signin") .loginProcessingUrl("/signin/authenticate") .failureUrl("/signin?param.error=bad_credentials") ... // more Spring security config goes here .and() .apply(new SpringSocialConfigurer()) .and().setSharedObject(ApplicationContext.class, context); } 39
  40. 40. Demo Spring Social Showcase
  41. 41. What’s New and Next for Spring Social?
  42. 42. Spring Social 1.1.0 Current Releases Spring Social [Core|Web|Security] 1.1.0.RC1 Spring Social Facebook 1.1.0.RC1 Spring Social Twitter 1.1.0.RC1 Spring Social LinkedIn 1.0.0.RC4 Spring Social GitHub 1.0.0.M4 42
  43. 43. Spring Social 1.1.0: What’s new? SocialAuthenticationFilter Automatic reconnect (ReconnectFilter) Simpler Java and XML configuration OAuth 2 Resource Owner Credentials Grant API Binding updates Twitter Streaming API support Facebook RealTime API support Facebook OpenGraph API support Facebook query language (FQL) support Facebook Canvas support 43
  44. 44. What’s next? Nothing is certain, but... Spring Social 1.1.0 GA in near future Lots of thought around... Spring Social and client-side JavaScript Spring Social and mobile applications Tighter integration with Spring Integration and Spring XD Spring Boot Support More options WRT connection repositories, security options, etc. Continued improvements and additions in API bindings More blogs, articles, and samples 44
  45. 45. What will you do with Spring Social? Spring Social is a Social Project...Join in! Forum: Issue tracking: SOCIAL, SOCIALFB, SOCIALTW, SOCIALLI, SOCIALGH, SOCIALTI Contribute: Fork on GitHub, submit pull requests, create new extensions 45
  46. 46. Thank you! @SpringSocial