Simple lightweight OAuth2 client for iOS 9 and above.
- Written in Objective-C and available as a CocoaPod.
- Built with AFNetworking 3.1
- Simple .plist configuration.
- Uses a
WKWebView
(via STKWebKitViewController) to avoid app switching whilst authenticating. - Securely persists tokens to
NSUserDefaults
. - Fires an
NSNotification
on sign in and sign out. - Automatic access token refreshing (if a refresh token is provided by your server).
OAuth2-ObjC is available through CocoaPods.
To install it, simply add the following line to your Podfile:
pod 'OAuth2-ObjC', :git => 'git://github.com/thomasgallagher/OAuth2-ObjC.git'
- If you do not already have one, create a custom URL scheme for your app and make a note of it - required to capture redirects back into your app from your OAuth2 server.
- Add
LSApplicationQueriesSchemes
as an array to yourInfo.plist
, then add your custom scheme name as the first item (without the :// suffix) as an entry - gives permission to the WKWebView to handle the re-direction back to your app. - Create a OAuth2ClientCredentials.plist file and fill it with your OAuth2 credentials - a sample version is provided in the example project.
- Add
#import "OAuth2Client.h"
to the top of yourAppDelegate.m
- Add the following method your your
AppDelegate.m
- caputures auth redirects back into your app from your OAuth2 server and forwards the server code to the library which subsequently exchanges it for an access token.
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
[[OAuth2Client sharedInstance] retrieveCodeFromUrl:url];
return NO;
}
- Add
#import "OAuth2Client.h"
to the ViewController in your project that you want to auth from. - Call
[[OAuth2Client sharedInstance] authenticateInViewController:self];
- a modal browser will show and begin the OAuth2 auth process. - When the user is returned - the library will fire a
kOAuth2SignedInNotification
notification.
You can use your access token from anywhere in your app - if your server sent a refresh token then this method will automatically refresh your expired access token with no extra work.
[[OAuth2Client sharedInstance] accessToken:^(NSString *accessToken) {
if (accessToken != nil) {
// Make your API call here using AF Networking 3.0
} else {
NSLog(@"API: Error: Access token is nil.");
}
}];
Use BOOL signedIn = [[OAuth2Client sharedInstance] signedIn];
if you want to check the signed in status of your user.
Use [[OAuth2Client sharedInstance] signOut];
to sign out - a kOAuth2SignedOutNotification
notification will be fired on completion.
Please submit issues and PRs for feature requests.
OAuth2-ObjC is available under the MIT license. See the LICENSE file for more info.