foursquare-android-oauth


Source link: https://github.com/foursquare/foursquare-android-oauth

foursquare-android-native-oauth

Foursquare native authentication makes it easier for your app's users to connect with Foursquare. Unlike web-based OAuth, native authentication re-uses the Foursquare app's user credentials, saving users the hassle of re-logging in to Foursquare within your app.

This repo includes an Android library that can be used in your own app. It also includes a simple application as an example of how to use the library.

Native auth will work on Foursquare versions 2013.08.16 and higher---if your users don't have the proper version installed, the library will give them an opportunity to download it in the Play Store (see "Using FoursquareOAuth").

Setting up your app

  1. Visit https://foursquare.com/developers/apps
  2. Create a new app or select from the list of apps that you have created.
  3. Generate a key hash of your developer certificate using this command: keytool -list -v -keystore mystore.keystore
  4. Paste the generated key hash into the Foursquare app console:
  5. Note that you can add multiple key hashes delimited by commas.
  6. Click "Save Changes".
  7. Copy the client id and secret as a string into your project. For security reasons, you should encrypt or obfuscate the id and secret.
  8. Include the internet permission in your app's AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET" />

Download

Grab via Maven:

<dependency>
<groupId>com.foursquare</groupId>
<artifactId>foursquare-android-oauth</artifactId>
<version>1.0.3</version> </dependency>

or Gradle:

compile 'com.foursquare:foursquare-android-oauth:1.0.3'

Using FoursquareOAuth

Obtaining an access code

Call FoursquareOAuth.getConnectIntent() with your application's client id to retrieve an intent that starts the Foursquare app for authentication. If the user doesn't have the app installed, or has an incompatible version installed, an intent that opens the Foursquare app page on Google Play is returned (you can check for this case with FoursquareOAuth.isPlayStoreIntent(intent)). Then call the startActivityForResult() method with the retrieved intent.

Intent intent = FoursquareOAuth.getConnectIntent(context, CLIENT_ID);
 startActivityForResult(intent, REQUEST_CODE_FSQ_CONNECT);

When the authorization completes, the onActivityResult() method of your initiating Activity or Fragment will be triggered. Call FoursquareOAuth.getAuthCodeFromResult() with the resultCode and data intent to obtain an AuthCodeResponse object.

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {

  switch (requestCode) {

case REQUEST_CODE_FSQ_CONNECT:

 AuthCodeResponse codeResponse = FoursquareOAuth.getAuthCodeFromResult(resultCode, data);

 /* ... */

 break;
  
}
 
}

The AuthCodeResponse object has two members:

  • code - The access code for the user.
  • exception - Exception of one of the following types:
    • FoursquareCancelException - User pressed the back button in the authorization screen.
    • FoursquareDenyException - User pressed the deny button in the authorization screen.
    • FoursquareUnsupportedVersionException - The version of the Foursquare app installed on the user's device is too old to support native auth.
    • FoursquareInvalidRequestException - Malformed connect request uri that the Foursquare app is not able to interpret, such as missing client id or version number. If you are using FoursquareOAuth.getConnectIntent() to start the oauth prcoess, you can ignore this exception as FoursquareOAuth creates the connect uri for you.
    • FoursquareOAuthException - An error occurred in the OAuth process. Call FoursquareOAuthException.getErrorCode() to obtain one of the error codes listed at http://tools.ietf.org/html/rfc6749#section-5.2
    • FoursquareInternalErrorException - An internal error occurred during authorization. Call exception.getCause() to inspect the original cause of the exception.

Obtaining an access token (server-side, recommended)

You should pass the returned access code to your own server and have it contact Foursquare's servers to convert the code to an access token. This is shown in step 3 in our code flow docs, but note that when making the request to /oauth2/access_token, you should omit the redirect_uri parameter. We recommend conducting the exchange for an access token on the server to avoid including your client secret in your app's binary.

Obtaining an access token (client-side)

WARNING: For security reasons, it is recommended that you not use the following method if possible. However, this helper method is provided for you to use if this is not possible for your app.

Add the TokenExchangeActivity to your AndroidManifest.xml

<activity

 android:name="com.foursquare.android.nativeoauth.TokenExchangeActivity"

 android:theme="@android:style/Theme.Dialog" />

The steps are very similar to obtaining an access code. Call FoursquareOAuth.getTokenExchangeIntent() with your application's client id, secret and access code to obtain an intent that starts the TokenExchangeActivity to convert a short-lived code into an access token. Then call the startActivityForResult() method with the retrieved intent.

Intent intent = FoursquareOAuth.getTokenExchangeIntent(context, CLIENT_ID, CLIENT_SECRET, authCode);
 startActivityForResult(intent, REQUEST_CODE_FSQ_TOKEN_EXCHANGE);

When the token exchange completes, the onActivityResult() method of your initiating Activity or Fragment will be triggered. Call FoursquareOAuth.getTokenFromResult() with the resultCode and data intent to obtain an AccessTokenResponse object.

@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {

  switch (requestCode) {

case REQUEST_CODE_FSQ_TOKEN_EXCHANGE:

 AccessTokenResponse tokenResponse = FoursquareOAuth.getTokenFromResult(resultCode, data);

 /* ... */

 break;
  
}
 
}

The AccessTokenResponse object has two members:

  • access_token - The access token of the user.
  • exception - Exception of one of the following types:
    • FoursquareOAuthException - An error occurred in the OAuth process. Call FoursquareOAuthException.getErrorCode() to obtain one of the error codes listed at http://tools.ietf.org/html/rfc6749#section-5.2.
    • FoursquareInternalErrorException - An internal error occurred while exchanging the code for a token.

License

Copyright (C) 2013 Foursquare Labs, Inc.  Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License. You may obtain a copy of the License at
  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 

More Information

See https://developer.foursquare.com for more information on how to use the Foursquare API.

Resources

This library allows you to create a list of items that are pinned by a floating label (text or image) on the left of the list.

An Rx wrapper for receiving results from startActivityForResult() as an Observable.

This library helps you to manage RecyclerViewAdapter easier.

A helpful and customizable Country Picker for your needs.

Pury is a profiling library for measuring time between multiple independent events. Events can be triggered with one of the annotations or with a method call. All events for a single scenario are united into one report.

Forcelayout is an Android library for visualizing data. You can drawing graph with spring-like attractive forces.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes