Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

WS

  • Loading branch information...
commit 12f9b0c0293470b3f2a12174d7fb79f2abc12db6 1 parent 9356a6b
@stigi stigi authored
Showing with 1,098 additions and 1,098 deletions.
  1. +1 −1  NXOAuth2Account+Private.h
  2. +2 −2 Sources/NSData+NXOAuth2.h
  3. +17 −17 Sources/NSData+NXOAuth2.m
  4. +2 −2 Sources/NSString+NXOAuth2.h
  5. +19 −19 Sources/NSString+NXOAuth2.m
  6. +2 −2 Sources/NSURL+NXOAuth2.h
  7. +20 −20 Sources/NSURL+NXOAuth2.m
  8. +2 −2 Sources/OAuth2Client/NXOAuth2.h
  9. +6 −6 Sources/OAuth2Client/NXOAuth2AccessToken.h
  10. +143 −143 Sources/OAuth2Client/NXOAuth2AccessToken.m
  11. +1 −1  Sources/OAuth2Client/NXOAuth2Account.h
  12. +7 −7 Sources/OAuth2Client/NXOAuth2Account.m
  13. +1 −1  Sources/OAuth2Client/NXOAuth2AccountStore.h
  14. +84 −84 Sources/OAuth2Client/NXOAuth2AccountStore.m
  15. +29 −29 Sources/OAuth2Client/NXOAuth2Client.h
  16. +195 −195 Sources/OAuth2Client/NXOAuth2Client.m
  17. +1 −1  Sources/OAuth2Client/NXOAuth2ClientDelegate.h
  18. +34 −34 Sources/OAuth2Client/NXOAuth2Connection.h
  19. +318 −318 Sources/OAuth2Client/NXOAuth2Connection.m
  20. +14 −14 Sources/OAuth2Client/NXOAuth2ConnectionDelegate.h
  21. +17 −17 Sources/OAuth2Client/NXOAuth2Constants.h
  22. +9 −9 Sources/OAuth2Client/NXOAuth2Constants.m
  23. +5 −5 Sources/OAuth2Client/NXOAuth2FileStreamWrapper.h
  24. +14 −14 Sources/OAuth2Client/NXOAuth2FileStreamWrapper.m
  25. +14 −14 Sources/OAuth2Client/NXOAuth2PostBodyPart.h
  26. +32 −32 Sources/OAuth2Client/NXOAuth2PostBodyPart.m
  27. +9 −9 Sources/OAuth2Client/NXOAuth2PostBodyStream.h
  28. +78 −78 Sources/OAuth2Client/NXOAuth2PostBodyStream.m
  29. +2 −2 Sources/OAuth2Client/NXOAuth2Request.h
  30. +17 −17 Sources/OAuth2Client/NXOAuth2Request.m
  31. +3 −3 Sources/OAuth2Client/NXOAuth2TrustDelegate.h
View
2  NXOAuth2Account+Private.h
@@ -7,7 +7,7 @@
// Copyright 2011 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
View
4 Sources/NSData+NXOAuth2.h
@@ -4,10 +4,10 @@
//
// Created by Thomas Kollbach on 18.05.11
//
-// Copyright 2011 nxtbgthng. All rights reserved.
+// Copyright 2011 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
View
34 Sources/NSData+NXOAuth2.m
@@ -4,10 +4,10 @@
//
// Created by Thomas Kollbach on 18.05.11
//
-// Copyright 2011 nxtbgthng. All rights reserved.
+// Copyright 2011 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
@@ -23,25 +23,25 @@ @implementation NSData (NXOAuth2)
- (NSData *)nx_SHA1Digest;
{
- uint8_t digest[CC_SHA1_DIGEST_LENGTH];
- CC_SHA1(self.bytes, (CC_LONG)self.length, digest);
-
- return [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
+ uint8_t digest[CC_SHA1_DIGEST_LENGTH];
+ CC_SHA1(self.bytes, (CC_LONG)self.length, digest);
+
+ return [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
}
- (NSString *)nx_SHA1Hexdigest;
{
- NSData *binDigest = [self nx_SHA1Digest];
- uint8_t digest[CC_SHA1_DIGEST_LENGTH];
- [binDigest getBytes:digest length:CC_SHA1_DIGEST_LENGTH];
-
- NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
-
- for (NSUInteger i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
- [output appendFormat:@"%02x", digest[i]];
- }
-
- return [output copy];
+ NSData *binDigest = [self nx_SHA1Digest];
+ uint8_t digest[CC_SHA1_DIGEST_LENGTH];
+ [binDigest getBytes:digest length:CC_SHA1_DIGEST_LENGTH];
+
+ NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
+
+ for (NSUInteger i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
+ [output appendFormat:@"%02x", digest[i]];
+ }
+
+ return [output copy];
}
View
4 Sources/NSString+NXOAuth2.h
@@ -4,10 +4,10 @@
//
// Created by Ullrich Schäfer on 07.10.09.
//
-// Copyright 2010 nxtbgthng. All rights reserved.
+// Copyright 2010 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
View
38 Sources/NSString+NXOAuth2.m
@@ -4,10 +4,10 @@
//
// Created by Ullrich Schäfer on 07.10.09.
//
-// Copyright 2010 nxtbgthng. All rights reserved.
+// Copyright 2010 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
@@ -19,7 +19,7 @@ @implementation NSString (NXOAuth2)
+ (NSString *)nxoauth2_stringWithUUID;
{
__autoreleasing NSString *result;
- CFUUIDRef theUUID = CFUUIDCreate(kCFAllocatorDefault);
+ CFUUIDRef theUUID = CFUUIDCreate(kCFAllocatorDefault);
result = (__bridge_transfer NSString *)CFUUIDCreateString(kCFAllocatorDefault, theUUID);
CFRelease(theUUID);
return result;
@@ -30,28 +30,28 @@ + (NSString *)nxoauth2_stringWithUUID;
+ (NSString *)nxoauth2_stringWithEncodedQueryParameters:(NSDictionary *)parameters;
{
-
- NSMutableArray *parameterPairs = [NSMutableArray array];
- for (NSString *key in [parameters allKeys]) {
- NSString *pair = [NSString stringWithFormat:@"%@=%@", [key nxoauth2_URLEncodedString], [[parameters objectForKey:key] nxoauth2_URLEncodedString]];
- [parameterPairs addObject:pair];
- }
- return [parameterPairs componentsJoinedByString:@"&"];
+
+ NSMutableArray *parameterPairs = [NSMutableArray array];
+ for (NSString *key in [parameters allKeys]) {
+ NSString *pair = [NSString stringWithFormat:@"%@=%@", [key nxoauth2_URLEncodedString], [[parameters objectForKey:key] nxoauth2_URLEncodedString]];
+ [parameterPairs addObject:pair];
+ }
+ return [parameterPairs componentsJoinedByString:@"&"];
}
- (NSDictionary *)nxoauth2_parametersFromEncodedQueryString;
{
- NSArray *encodedParameterPairs = [self componentsSeparatedByString:@"&"];
+ NSArray *encodedParameterPairs = [self componentsSeparatedByString:@"&"];
NSMutableDictionary *requestParameters = [NSMutableDictionary dictionary];
for (NSString *encodedPair in encodedParameterPairs) {
NSArray *encodedPairElements = [encodedPair componentsSeparatedByString:@"="];
- if (encodedPairElements.count == 2) {
- [requestParameters setValue:[[encodedPairElements objectAtIndex:1] nxoauth2_URLDecodedString]
- forKey:[[encodedPairElements objectAtIndex:0] nxoauth2_URLDecodedString]];
- }
+ if (encodedPairElements.count == 2) {
+ [requestParameters setValue:[[encodedPairElements objectAtIndex:1] nxoauth2_URLDecodedString]
+ forKey:[[encodedPairElements objectAtIndex:0] nxoauth2_URLDecodedString]];
+ }
}
- return requestParameters;
+ return requestParameters;
}
@@ -60,13 +60,13 @@ - (NSDictionary *)nxoauth2_parametersFromEncodedQueryString;
- (NSString *)nxoauth2_URLEncodedString;
{
- CFStringRef cfResult = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, //Allocator
+ CFStringRef cfResult = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, //Allocator
(__bridge CFStringRef)self, //Original String
NULL, //Characters to leave unescaped
(CFStringRef)@"!*'();:@&=+$,/?%#[]", //Legal Characters to be escaped
kCFStringEncodingUTF8); //Encoding
__autoreleasing NSString *result = (__bridge_transfer NSString *)cfResult;
- return result;
+ return result;
}
- (NSString *)nxoauth2_URLDecodedString;
@@ -76,7 +76,7 @@ - (NSString *)nxoauth2_URLDecodedString;
CFSTR(""),
kCFStringEncodingUTF8);
__autoreleasing NSString *result = (__bridge_transfer NSString *)cfResult;
- return result;
+ return result;
}
@end
View
4 Sources/NSURL+NXOAuth2.h
@@ -4,10 +4,10 @@
//
// Created by Ullrich Schäfer on 07.10.09.
//
-// Copyright 2010 nxtbgthng. All rights reserved.
+// Copyright 2010 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
View
40 Sources/NSURL+NXOAuth2.m
@@ -4,10 +4,10 @@
//
// Created by Ullrich Schäfer on 07.10.09.
//
-// Copyright 2010 nxtbgthng. All rights reserved.
+// Copyright 2010 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
@@ -19,32 +19,32 @@
@implementation NSURL (NXOAuth2)
- (NSURL *)nxoauth2_URLByAddingParameters:(NSDictionary *)parameterDictionary {
- if (!parameterDictionary || [parameterDictionary count] == 0) {
- return self;
- }
-
- NSString *newParameterString = [NSString nxoauth2_stringWithEncodedQueryParameters:parameterDictionary];
-
- NSString *absoluteString = [self absoluteString];
- if ([absoluteString rangeOfString:@"?"].location == NSNotFound) { // append parameters?
- absoluteString = [NSString stringWithFormat:@"%@?%@", absoluteString, newParameterString];
- } else {
- absoluteString = [NSString stringWithFormat:@"%@&%@", absoluteString, newParameterString];
- }
-
- return [NSURL URLWithString:absoluteString];
+ if (!parameterDictionary || [parameterDictionary count] == 0) {
+ return self;
+ }
+
+ NSString *newParameterString = [NSString nxoauth2_stringWithEncodedQueryParameters:parameterDictionary];
+
+ NSString *absoluteString = [self absoluteString];
+ if ([absoluteString rangeOfString:@"?"].location == NSNotFound) { // append parameters?
+ absoluteString = [NSString stringWithFormat:@"%@?%@", absoluteString, newParameterString];
+ } else {
+ absoluteString = [NSString stringWithFormat:@"%@&%@", absoluteString, newParameterString];
+ }
+
+ return [NSURL URLWithString:absoluteString];
}
- (NSString *)nxoauth2_valueForQueryParameterKey:(NSString *)key;
{
- NSString *queryString = [self query];
- NSDictionary *parameters = [queryString nxoauth2_parametersFromEncodedQueryString];
- return [parameters objectForKey:key];
+ NSString *queryString = [self query];
+ NSDictionary *parameters = [queryString nxoauth2_parametersFromEncodedQueryString];
+ return [parameters objectForKey:key];
}
- (NSURL *)nxoauth2_URLWithoutQueryString;
{
- return [NSURL URLWithString:[self nxoauth2_URLStringWithoutQueryString]];
+ return [NSURL URLWithString:[self nxoauth2_URLStringWithoutQueryString]];
}
- (NSString *)nxoauth2_URLStringWithoutQueryString;
View
4 Sources/OAuth2Client/NXOAuth2.h
@@ -4,10 +4,10 @@
//
// Created by Ullrich Schäfer on 13.09.10.
//
-// Copyright 2010 nxtbgthng. All rights reserved.
+// Copyright 2010 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
View
12 Sources/OAuth2Client/NXOAuth2AccessToken.h
@@ -4,10 +4,10 @@
//
// Created by Ullrich Schäfer on 27.08.10.
//
-// Copyright 2010 nxtbgthng. All rights reserved.
+// Copyright 2010 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
@@ -17,10 +17,10 @@
@interface NXOAuth2AccessToken : NSObject <NSCoding> {
@private
- NSString *accessToken;
- NSString *refreshToken;
- NSDate *expiresAt;
- NSSet *scope;
+ NSString *accessToken;
+ NSString *refreshToken;
+ NSDate *expiresAt;
+ NSSet *scope;
NSString *responseBody;
}
@property (nonatomic, readonly) NSString *accessToken;
View
286 Sources/OAuth2Client/NXOAuth2AccessToken.m
@@ -4,10 +4,10 @@
//
// Created by Ullrich Schäfer on 27.08.10.
//
-// Copyright 2010 nxtbgthng. All rights reserved.
+// Copyright 2010 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
@@ -46,35 +46,35 @@ + (id)tokenWithResponseBody:(NSString *)theResponseBody;
}
jsonDict = dict;
}
- NSString *expiresIn = [jsonDict objectForKey:@"expires_in"];
- NSString *anAccessToken = [jsonDict objectForKey:@"access_token"];
- NSString *aRefreshToken = [jsonDict objectForKey:@"refresh_token"];
- NSString *scopeString = [jsonDict objectForKey:@"scope"];
-
- NSSet *scope = nil;
- if (scopeString) {
- scope = [NSSet setWithArray:[scopeString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
- }
-
- NSDate *expiryDate = nil;
- if (expiresIn) {
- expiryDate = [NSDate dateWithTimeIntervalSinceNow:[expiresIn integerValue]];
- }
- return [[[self class] alloc] initWithAccessToken:anAccessToken
- refreshToken:aRefreshToken
- expiresAt:expiryDate
- scope:scope
+ NSString *expiresIn = [jsonDict objectForKey:@"expires_in"];
+ NSString *anAccessToken = [jsonDict objectForKey:@"access_token"];
+ NSString *aRefreshToken = [jsonDict objectForKey:@"refresh_token"];
+ NSString *scopeString = [jsonDict objectForKey:@"scope"];
+
+ NSSet *scope = nil;
+ if (scopeString) {
+ scope = [NSSet setWithArray:[scopeString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
+ }
+
+ NSDate *expiryDate = nil;
+ if (expiresIn) {
+ expiryDate = [NSDate dateWithTimeIntervalSinceNow:[expiresIn integerValue]];
+ }
+ return [[[self class] alloc] initWithAccessToken:anAccessToken
+ refreshToken:aRefreshToken
+ expiresAt:expiryDate
+ scope:scope
responseBody:theResponseBody];
}
- (id)initWithAccessToken:(NSString *)anAccessToken;
{
- return [self initWithAccessToken:anAccessToken refreshToken:nil expiresAt:nil];
+ return [self initWithAccessToken:anAccessToken refreshToken:nil expiresAt:nil];
}
- (id)initWithAccessToken:(NSString *)anAccessToken refreshToken:(NSString *)aRefreshToken expiresAt:(NSDate *)anExpiryDate;
{
- return [[[self class] alloc] initWithAccessToken:anAccessToken
+ return [[[self class] alloc] initWithAccessToken:anAccessToken
refreshToken:aRefreshToken
expiresAt:anExpiryDate
scope:nil];
@@ -82,7 +82,7 @@ - (id)initWithAccessToken:(NSString *)anAccessToken refreshToken:(NSString *)aRe
- (id)initWithAccessToken:(NSString *)anAccessToken refreshToken:(NSString *)aRefreshToken expiresAt:(NSDate *)anExpiryDate scope:(NSSet *)aScope;
{
- return [[[self class] alloc] initWithAccessToken:anAccessToken
+ return [[[self class] alloc] initWithAccessToken:anAccessToken
refreshToken:aRefreshToken
expiresAt:anExpiryDate
scope:aScope
@@ -91,21 +91,21 @@ - (id)initWithAccessToken:(NSString *)anAccessToken refreshToken:(NSString *)aRe
- (id)initWithAccessToken:(NSString *)anAccessToken refreshToken:(NSString *)aRefreshToken expiresAt:(NSDate *)anExpiryDate scope:(NSSet *)aScope responseBody:(NSString *)aResponseBody;
{
- // a token object without an actual token is not what we want!
+ // a token object without an actual token is not what we want!
NSAssert1(anAccessToken, @"No token from token response: %@", aResponseBody);
- if (anAccessToken == nil) {
- return nil;
- }
-
- self = [super init];
- if (self) {
- accessToken = [anAccessToken copy];
- refreshToken = [aRefreshToken copy];
- expiresAt = [anExpiryDate copy];
- scope = aScope ? [aScope copy] : [[NSSet alloc] init];
+ if (anAccessToken == nil) {
+ return nil;
+ }
+
+ self = [super init];
+ if (self) {
+ accessToken = [anAccessToken copy];
+ refreshToken = [aRefreshToken copy];
+ expiresAt = [anExpiryDate copy];
+ scope = aScope ? [aScope copy] : [[NSSet alloc] init];
responseBody = [aResponseBody copy];
- }
- return self;
+ }
+ return self;
}
@@ -120,18 +120,18 @@ - (id)initWithAccessToken:(NSString *)anAccessToken refreshToken:(NSString *)aRe
- (BOOL)doesExpire;
{
- return (expiresAt != nil);
+ return (expiresAt != nil);
}
- (BOOL)hasExpired;
{
- return ([[NSDate date] earlierDate:expiresAt] == expiresAt);
+ return ([[NSDate date] earlierDate:expiresAt] == expiresAt);
}
- (NSString *)description;
{
- return [NSString stringWithFormat:@"<NXOAuth2Token token:%@ refreshToken:%@ expiresAt:%@>", self.accessToken, self.refreshToken, self.expiresAt];
+ return [NSString stringWithFormat:@"<NXOAuth2Token token:%@ refreshToken:%@ expiresAt:%@>", self.accessToken, self.refreshToken, self.expiresAt];
}
@@ -139,31 +139,31 @@ - (NSString *)description;
- (void)encodeWithCoder:(NSCoder *)aCoder
{
- [aCoder encodeObject:accessToken forKey:@"accessToken"];
- [aCoder encodeObject:refreshToken forKey:@"refreshToken"];
- [aCoder encodeObject:expiresAt forKey:@"expiresAt"];
+ [aCoder encodeObject:accessToken forKey:@"accessToken"];
+ [aCoder encodeObject:refreshToken forKey:@"refreshToken"];
+ [aCoder encodeObject:expiresAt forKey:@"expiresAt"];
[aCoder encodeObject:scope forKey:@"scope"];
[aCoder encodeObject:responseBody forKey:@"responseBody"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
- NSString *decodedAccessToken = [aDecoder decodeObjectForKey:@"accessToken"];
-
- // a token object without an actual token is not what we want!
- if (decodedAccessToken == nil) {
- return nil;
- }
-
+ NSString *decodedAccessToken = [aDecoder decodeObjectForKey:@"accessToken"];
+
+ // a token object without an actual token is not what we want!
+ if (decodedAccessToken == nil) {
+ return nil;
+ }
+
self = [super init];
- if (self) {
- accessToken = [decodedAccessToken copy];
- refreshToken = [[aDecoder decodeObjectForKey:@"refreshToken"] copy];
- expiresAt = [[aDecoder decodeObjectForKey:@"expiresAt"] copy];
+ if (self) {
+ accessToken = [decodedAccessToken copy];
+ refreshToken = [[aDecoder decodeObjectForKey:@"refreshToken"] copy];
+ expiresAt = [[aDecoder decodeObjectForKey:@"expiresAt"] copy];
scope = [[aDecoder decodeObjectForKey:@"scope"] copy];
responseBody = [[aDecoder decodeObjectForKey:@"responseBody"] copy];
- }
- return self;
+ }
+ return self;
}
@@ -171,87 +171,87 @@ - (id)initWithCoder:(NSCoder *)aDecoder
+ (NSString *)serviceNameWithProvider:(NSString *)provider;
{
- NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
-
- return [NSString stringWithFormat:@"%@::OAuth2::%@", appName, provider];
+ NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
+
+ return [NSString stringWithFormat:@"%@::OAuth2::%@", appName, provider];
}
#if TARGET_OS_IPHONE
+ (id)tokenFromDefaultKeychainWithServiceProviderName:(NSString *)provider;
{
- NSString *serviceName = [[self class] serviceNameWithProvider:provider];
- NSDictionary *result = nil;
- NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
- (__bridge NSString *)kSecClassGenericPassword, kSecClass,
- serviceName, kSecAttrService,
- kCFBooleanTrue, kSecReturnAttributes,
- nil];
+ NSString *serviceName = [[self class] serviceNameWithProvider:provider];
+ NSDictionary *result = nil;
+ NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
+ (__bridge NSString *)kSecClassGenericPassword, kSecClass,
+ serviceName, kSecAttrService,
+ kCFBooleanTrue, kSecReturnAttributes,
+ nil];
CFTypeRef cfResult = nil;
- OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &cfResult);
+ OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &cfResult);
result = (__bridge_transfer NSDictionary *)cfResult;
- if (status != noErr) {
- NSAssert1(status == errSecItemNotFound, @"unexpected error while fetching token from keychain: %d", status);
- return nil;
- }
-
- return [NSKeyedUnarchiver unarchiveObjectWithData:[result objectForKey:(__bridge NSString *)kSecAttrGeneric]];
+ if (status != noErr) {
+ NSAssert1(status == errSecItemNotFound, @"unexpected error while fetching token from keychain: %d", status);
+ return nil;
+ }
+
+ return [NSKeyedUnarchiver unarchiveObjectWithData:[result objectForKey:(__bridge NSString *)kSecAttrGeneric]];
}
- (void)storeInDefaultKeychainWithServiceProviderName:(NSString *)provider;
{
- NSString *serviceName = [[self class] serviceNameWithProvider:provider];
- NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self];
- NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
- (__bridge NSString *)kSecClassGenericPassword, kSecClass,
- serviceName, kSecAttrService,
- @"OAuth 2 Access Token", kSecAttrLabel,
- data, kSecAttrGeneric,
- nil];
- [self removeFromDefaultKeychainWithServiceProviderName:provider];
- OSStatus __attribute__((unused)) err = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
- NSAssert1(err == noErr, @"error while adding token to keychain: %d", err);
+ NSString *serviceName = [[self class] serviceNameWithProvider:provider];
+ NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self];
+ NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
+ (__bridge NSString *)kSecClassGenericPassword, kSecClass,
+ serviceName, kSecAttrService,
+ @"OAuth 2 Access Token", kSecAttrLabel,
+ data, kSecAttrGeneric,
+ nil];
+ [self removeFromDefaultKeychainWithServiceProviderName:provider];
+ OSStatus __attribute__((unused)) err = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
+ NSAssert1(err == noErr, @"error while adding token to keychain: %d", err);
}
- (void)removeFromDefaultKeychainWithServiceProviderName:(NSString *)provider;
{
- NSString *serviceName = [[self class] serviceNameWithProvider:provider];
- NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
- (__bridge NSString *)kSecClassGenericPassword, kSecClass,
- serviceName, kSecAttrService,
- nil];
- OSStatus __attribute__((unused)) err = SecItemDelete((__bridge CFDictionaryRef)query);
- NSAssert1((err == noErr || err == errSecItemNotFound), @"error while deleting token from keychain: %d", err);
+ NSString *serviceName = [[self class] serviceNameWithProvider:provider];
+ NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
+ (__bridge NSString *)kSecClassGenericPassword, kSecClass,
+ serviceName, kSecAttrService,
+ nil];
+ OSStatus __attribute__((unused)) err = SecItemDelete((__bridge CFDictionaryRef)query);
+ NSAssert1((err == noErr || err == errSecItemNotFound), @"error while deleting token from keychain: %d", err);
}
#else
+ (id)tokenFromDefaultKeychainWithServiceProviderName:(NSString *)provider;
{
- NSString *serviceName = [[self class] serviceNameWithProvider:provider];
-
- SecKeychainItemRef item = nil;
- OSStatus err = SecKeychainFindGenericPassword(NULL,
- strlen([serviceName UTF8String]),
- [serviceName UTF8String],
- 0,
- NULL,
- NULL,
- NULL,
- &item);
- if (err != noErr) {
- NSAssert1(err == errSecItemNotFound, @"unexpected error while fetching token from keychain: %d", err);
- return nil;
- }
+ NSString *serviceName = [[self class] serviceNameWithProvider:provider];
+
+ SecKeychainItemRef item = nil;
+ OSStatus err = SecKeychainFindGenericPassword(NULL,
+ strlen([serviceName UTF8String]),
+ [serviceName UTF8String],
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ &item);
+ if (err != noErr) {
+ NSAssert1(err == errSecItemNotFound, @"unexpected error while fetching token from keychain: %d", err);
+ return nil;
+ }
// from Advanced Mac OS X Programming, ch. 16
UInt32 length;
char *password;
- NSData *result = nil;
+ NSData *result = nil;
SecKeychainAttribute attributes[8];
SecKeychainAttributeList list;
-
+
attributes[0].tag = kSecAccountItemAttr;
attributes[1].tag = kSecDescriptionItemAttr;
attributes[2].tag = kSecLabelItemAttr;
@@ -263,56 +263,56 @@ + (id)tokenFromDefaultKeychainWithServiceProviderName:(NSString *)provider;
err = SecKeychainItemCopyContent(item, NULL, &list, &length, (void **)&password);
if (err == noErr) {
if (password != NULL) {
- result = [NSData dataWithBytes:password length:length];
+ result = [NSData dataWithBytes:password length:length];
}
SecKeychainItemFreeContent(&list, password);
} else {
- // TODO find out why this always works in i386 and always fails on ppc
- NSLog(@"Error from SecKeychainItemCopyContent: %d", err);
+ // TODO find out why this always works in i386 and always fails on ppc
+ NSLog(@"Error from SecKeychainItemCopyContent: %d", err);
return nil;
}
CFRelease(item);
- return [NSKeyedUnarchiver unarchiveObjectWithData:result];
+ return [NSKeyedUnarchiver unarchiveObjectWithData:result];
}
- (void)storeInDefaultKeychainWithServiceProviderName:(NSString *)provider;
{
- [self removeFromDefaultKeychainWithServiceProviderName:provider];
- NSString *serviceName = [[self class] serviceNameWithProvider:provider];
- NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self];
-
- OSStatus __attribute__((unused))err = SecKeychainAddGenericPassword(NULL,
- strlen([serviceName UTF8String]),
- [serviceName UTF8String],
- 0,
- NULL,
- [data length],
- [data bytes],
- NULL);
-
- NSAssert1(err == noErr, @"error while adding token to keychain: %d", err);
+ [self removeFromDefaultKeychainWithServiceProviderName:provider];
+ NSString *serviceName = [[self class] serviceNameWithProvider:provider];
+ NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self];
+
+ OSStatus __attribute__((unused))err = SecKeychainAddGenericPassword(NULL,
+ strlen([serviceName UTF8String]),
+ [serviceName UTF8String],
+ 0,
+ NULL,
+ [data length],
+ [data bytes],
+ NULL);
+
+ NSAssert1(err == noErr, @"error while adding token to keychain: %d", err);
}
- (void)removeFromDefaultKeychainWithServiceProviderName:(NSString *)provider;
{
- NSString *serviceName = [[self class] serviceNameWithProvider:provider];
- SecKeychainItemRef item = nil;
- OSStatus err = SecKeychainFindGenericPassword(NULL,
- strlen([serviceName UTF8String]),
- [serviceName UTF8String],
- 0,
- NULL,
- NULL,
- NULL,
- &item);
- NSAssert1((err == noErr || err == errSecItemNotFound), @"error while deleting token from keychain: %d", err);
- if (err == noErr) {
- err = SecKeychainItemDelete(item);
- }
- if (item) {
- CFRelease(item);
- }
- NSAssert1((err == noErr || err == errSecItemNotFound), @"error while deleting token from keychain: %d", err);
+ NSString *serviceName = [[self class] serviceNameWithProvider:provider];
+ SecKeychainItemRef item = nil;
+ OSStatus err = SecKeychainFindGenericPassword(NULL,
+ strlen([serviceName UTF8String]),
+ [serviceName UTF8String],
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ &item);
+ NSAssert1((err == noErr || err == errSecItemNotFound), @"error while deleting token from keychain: %d", err);
+ if (err == noErr) {
+ err = SecKeychainItemDelete(item);
+ }
+ if (item) {
+ CFRelease(item);
+ }
+ NSAssert1((err == noErr || err == errSecItemNotFound), @"error while deleting token from keychain: %d", err);
}
#endif
View
2  Sources/OAuth2Client/NXOAuth2Account.h
@@ -7,7 +7,7 @@
// Copyright 2011 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
View
14 Sources/OAuth2Client/NXOAuth2Account.m
@@ -7,7 +7,7 @@
// Copyright 2011 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
@@ -173,21 +173,21 @@ - (void)oauthClient:(NXOAuth2Client *)client didFailToGetAccessTokenWithError:(N
- (void)encodeWithCoder:(NSCoder *)aCoder
{
- [aCoder encodeObject:identifier forKey:@"identifier"];
+ [aCoder encodeObject:identifier forKey:@"identifier"];
[aCoder encodeObject:accountType forKey:@"accountType"];
- [aCoder encodeObject:accessToken forKey:@"accessToken"];
+ [aCoder encodeObject:accessToken forKey:@"accessToken"];
[aCoder encodeObject:userData forKey:@"userData"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
- if (self = [super init]) {
+ if (self = [super init]) {
userData = [aDecoder decodeObjectForKey:@"userData"];
accessToken = [aDecoder decodeObjectForKey:@"accessToken"];
- accountType = [[aDecoder decodeObjectForKey:@"accountType"] copy];
+ accountType = [[aDecoder decodeObjectForKey:@"accountType"] copy];
identifier = [[aDecoder decodeObjectForKey:@"identifier"] copy];
- }
- return self;
+ }
+ return self;
}
@end
View
2  Sources/OAuth2Client/NXOAuth2AccountStore.h
@@ -7,7 +7,7 @@
// Copyright 2011 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
View
168 Sources/OAuth2Client/NXOAuth2AccountStore.m
@@ -7,7 +7,7 @@
// Copyright 2011 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
@@ -172,7 +172,7 @@ - (void)requestAccessToAccountWithType:(NSString *)accountType;
[client requestAccess];
}
-- (void)requestAccessToAccountWithType:(NSString *)accountType
+- (void)requestAccessToAccountWithType:(NSString *)accountType
withPreparedAuthorizationURLHandler:(NXOAuth2PreparedAuthorizationURLHandler)aPreparedAuthorizationURLHandler;
{
NSAssert(aPreparedAuthorizationURLHandler, @"Prepared Authorization Handler must not be nil.");
@@ -221,7 +221,7 @@ - (void)setClientID:(NSString *)aClientID
aSecret, kNXOAuth2AccountStoreConfigurationSecret,
anAuthorizationURL, kNXOAuth2AccountStoreConfigurationAuthorizeURL,
aTokenURL, kNXOAuth2AccountStoreConfigurationTokenURL,
- aRedirectURL, kNXOAuth2AccountStoreConfigurationRedirectURL, nil]
+ aRedirectURL, kNXOAuth2AccountStoreConfigurationRedirectURL, nil]
forAccountType:anAccountType];
}
@@ -351,7 +351,7 @@ - (NXOAuth2Client *)pendingOAuthClientForAccountType:(NSString *)accountType;
[self.pendingOAuthClients setObject:client forKey:accountType];
}
}
- return client;
+ return client;
}
- (NSString *)accountTypeOfPendingOAuthClient:(NXOAuth2Client *)oauthClient;
@@ -374,7 +374,7 @@ - (NSString *)accountTypeOfPendingOAuthClient:(NXOAuth2Client *)oauthClient;
#pragma mark NXOAuth2ClientDelegate
- (void)oauthClientNeedsAuthentication:(NXOAuth2Client *)client;
-{
+{
NSString *accountType = [self accountTypeOfPendingOAuthClient:client];
NSDictionary *configuration;
@@ -406,12 +406,12 @@ - (void)oauthClientDidGetAccessToken:(NXOAuth2Client *)client;
[NXOAuth2AccountStore storeAccountsInDefaultKeychain:self.accountsDict];
}
- NSDictionary *userInfo = [NSDictionary dictionaryWithObject:account
- forKey:NXOAuth2AccountStoreNewAccountUserInfoKey];
-
+ NSDictionary *userInfo = [NSDictionary dictionaryWithObject:account
+ forKey:NXOAuth2AccountStoreNewAccountUserInfoKey];
+
[[NSNotificationCenter defaultCenter] postNotificationName:NXOAuth2AccountStoreAccountsDidChangeNotification
- object:self
- userInfo:userInfo];
+ object:self
+ userInfo:userInfo];
}
- (void)oauthClientDidLoseAccessToken:(NXOAuth2Client *)client;
@@ -497,7 +497,7 @@ - (void)accountDidLoseAccessToken:(NSNotification *)aNotification;
+ (NSString *)keychainServiceName;
{
NSString *appName = [[NSBundle mainBundle] bundleIdentifier];
- return [NSString stringWithFormat:@"%@::NXOAuth2AccountStore", appName];
+ return [NSString stringWithFormat:@"%@::NXOAuth2AccountStore", appName];
}
#if TARGET_OS_IPHONE
@@ -507,21 +507,21 @@ + (NSDictionary *)accountsFromDefaultKeychain;
NSString *serviceName = [self keychainServiceName];
NSDictionary *result = nil;
- NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
- (__bridge NSString *)kSecClassGenericPassword, kSecClass,
- serviceName, kSecAttrService,
- kCFBooleanTrue, kSecReturnAttributes,
- nil];
+ NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
+ (__bridge NSString *)kSecClassGenericPassword, kSecClass,
+ serviceName, kSecAttrService,
+ kCFBooleanTrue, kSecReturnAttributes,
+ nil];
CFTypeRef cfResult = nil;
- OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &cfResult);
+ OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &cfResult);
result = (__bridge_transfer NSDictionary *)cfResult;
-
- if (status != noErr) {
- NSAssert1(status == errSecItemNotFound, @"Unexpected error while fetching accounts from keychain: %d", status);
- return nil;
- }
-
- return [NSKeyedUnarchiver unarchiveObjectWithData:[result objectForKey:(__bridge NSString *)kSecAttrGeneric]];
+
+ if (status != noErr) {
+ NSAssert1(status == errSecItemNotFound, @"Unexpected error while fetching accounts from keychain: %d", status);
+ return nil;
+ }
+
+ return [NSKeyedUnarchiver unarchiveObjectWithData:[result objectForKey:(__bridge NSString *)kSecAttrGeneric]];
}
+ (void)storeAccountsInDefaultKeychain:(NSDictionary *)accounts;
@@ -531,25 +531,25 @@ + (void)storeAccountsInDefaultKeychain:(NSDictionary *)accounts;
NSString *serviceName = [self keychainServiceName];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:accounts];
- NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
- (__bridge NSString *)kSecClassGenericPassword, kSecClass,
- serviceName, kSecAttrService,
- @"OAuth 2 Account Store", kSecAttrLabel,
- data, kSecAttrGeneric,
- nil];
- OSStatus __attribute__((unused)) err = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
- NSAssert1(err == noErr, @"Error while adding token to keychain: %d", err);
+ NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
+ (__bridge NSString *)kSecClassGenericPassword, kSecClass,
+ serviceName, kSecAttrService,
+ @"OAuth 2 Account Store", kSecAttrLabel,
+ data, kSecAttrGeneric,
+ nil];
+ OSStatus __attribute__((unused)) err = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
+ NSAssert1(err == noErr, @"Error while adding token to keychain: %d", err);
}
+ (void)removeFromDefaultKeychain;
{
NSString *serviceName = [self keychainServiceName];
NSDictionary *query = [NSDictionary dictionaryWithObjectsAndKeys:
- (__bridge NSString *)kSecClassGenericPassword, kSecClass,
- serviceName, kSecAttrService,
- nil];
- OSStatus __attribute__((unused)) err = SecItemDelete((__bridge CFDictionaryRef)query);
- NSAssert1((err == noErr || err == errSecItemNotFound), @"Error while deleting token from keychain: %d", err);
+ (__bridge NSString *)kSecClassGenericPassword, kSecClass,
+ serviceName, kSecAttrService,
+ nil];
+ OSStatus __attribute__((unused)) err = SecItemDelete((__bridge CFDictionaryRef)query);
+ NSAssert1((err == noErr || err == errSecItemNotFound), @"Error while deleting token from keychain: %d", err);
}
@@ -559,27 +559,27 @@ + (NSDictionary *)accountsFromDefaultKeychain;
{
NSString *serviceName = [self keychainServiceName];
- SecKeychainItemRef item = nil;
- OSStatus err = SecKeychainFindGenericPassword(NULL,
- strlen([serviceName UTF8String]),
- [serviceName UTF8String],
- 0,
- NULL,
- NULL,
- NULL,
- &item);
- if (err != noErr) {
- NSAssert1(err == errSecItemNotFound, @"Unexpected error while fetching accounts from keychain: %d", err);
- return nil;
- }
+ SecKeychainItemRef item = nil;
+ OSStatus err = SecKeychainFindGenericPassword(NULL,
+ strlen([serviceName UTF8String]),
+ [serviceName UTF8String],
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ &item);
+ if (err != noErr) {
+ NSAssert1(err == errSecItemNotFound, @"Unexpected error while fetching accounts from keychain: %d", err);
+ return nil;
+ }
// from Advanced Mac OS X Programming, ch. 16
UInt32 length;
char *password;
- NSData *result = nil;
+ NSData *result = nil;
SecKeychainAttribute attributes[8];
SecKeychainAttributeList list;
-
+
attributes[0].tag = kSecAccountItemAttr;
attributes[1].tag = kSecDescriptionItemAttr;
attributes[2].tag = kSecLabelItemAttr;
@@ -591,16 +591,16 @@ + (NSDictionary *)accountsFromDefaultKeychain;
err = SecKeychainItemCopyContent(item, NULL, &list, &length, (void **)&password);
if (err == noErr) {
if (password != NULL) {
- result = [NSData dataWithBytes:password length:length];
+ result = [NSData dataWithBytes:password length:length];
}
SecKeychainItemFreeContent(&list, password);
} else {
- // TODO find out why this always works in i386 and always fails on ppc
- NSLog(@"Error from SecKeychainItemCopyContent: %d", err);
+ // TODO find out why this always works in i386 and always fails on ppc
+ NSLog(@"Error from SecKeychainItemCopyContent: %d", err);
return nil;
}
CFRelease(item);
- return [NSKeyedUnarchiver unarchiveObjectWithData:result];
+ return [NSKeyedUnarchiver unarchiveObjectWithData:result];
}
+ (void)storeAccountsInDefaultKeychain:(NSDictionary *)accounts;
@@ -609,41 +609,41 @@ + (void)storeAccountsInDefaultKeychain:(NSDictionary *)accounts;
NSString *serviceName = [self keychainServiceName];
- NSData *data = [NSKeyedArchiver archivedDataWithRootObject:accounts];
-
- OSStatus __attribute__((unused))err = SecKeychainAddGenericPassword(NULL,
- strlen([serviceName UTF8String]),
- [serviceName UTF8String],
- 0,
- NULL,
- [data length],
- [data bytes],
- NULL);
+ NSData *data = [NSKeyedArchiver archivedDataWithRootObject:accounts];
+
+ OSStatus __attribute__((unused))err = SecKeychainAddGenericPassword(NULL,
+ strlen([serviceName UTF8String]),
+ [serviceName UTF8String],
+ 0,
+ NULL,
+ [data length],
+ [data bytes],
+ NULL);
- NSAssert1(err == noErr, @"Error while storing accounts in keychain: %d", err);
+ NSAssert1(err == noErr, @"Error while storing accounts in keychain: %d", err);
}
+ (void)removeFromDefaultKeychain;
{
NSString *serviceName = [self keychainServiceName];
-
+
SecKeychainItemRef item = nil;
- OSStatus err = SecKeychainFindGenericPassword(NULL,
- strlen([serviceName UTF8String]),
- [serviceName UTF8String],
- 0,
- NULL,
- NULL,
- NULL,
- &item);
- NSAssert1((err == noErr || err == errSecItemNotFound), @"Error while deleting accounts from keychain: %d", err);
- if (err == noErr) {
- err = SecKeychainItemDelete(item);
- }
- if (item) {
- CFRelease(item);
- }
- NSAssert1((err == noErr || err == errSecItemNotFound), @"Error while deleting accounts from keychain: %d", err);
+ OSStatus err = SecKeychainFindGenericPassword(NULL,
+ strlen([serviceName UTF8String]),
+ [serviceName UTF8String],
+ 0,
+ NULL,
+ NULL,
+ NULL,
+ &item);
+ NSAssert1((err == noErr || err == errSecItemNotFound), @"Error while deleting accounts from keychain: %d", err);
+ if (err == noErr) {
+ err = SecKeychainItemDelete(item);
+ }
+ if (item) {
+ CFRelease(item);
+ }
+ NSAssert1((err == noErr || err == errSecItemNotFound), @"Error while deleting accounts from keychain: %d", err);
}
#endif
View
58 Sources/OAuth2Client/NXOAuth2Client.h
@@ -4,10 +4,10 @@
//
// Created by Ullrich Schäfer on 27.08.10.
//
-// Copyright 2010 nxtbgthng. All rights reserved.
+// Copyright 2010 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
@@ -34,26 +34,26 @@ extern NSString * const NXOAuth2ClientConnectionContextTokenRefresh;
@interface NXOAuth2Client : NSObject <NXOAuth2ConnectionDelegate> {
@protected
BOOL authenticating;
- BOOL persistent;
+ BOOL persistent;
- NSString *clientId;
- NSString *clientSecret;
-
+ NSString *clientId;
+ NSString *clientSecret;
+
NSSet *desiredScope;
- NSString *userAgent;
-
- // server information
- NSURL *authorizeURL;
- NSURL *tokenURL;
-
- // token exchange
- NXOAuth2Connection *authConnection;
- NXOAuth2AccessToken *accessToken;
- NSMutableArray *waitingConnections; //for connections that are waiting for successful authorisation
- NSInteger refreshConnectionDidRetryCount;
-
- // delegates
- NSObject<NXOAuth2ClientDelegate>* __unsafe_unretained delegate; // assigned
+ NSString *userAgent;
+
+ // server information
+ NSURL *authorizeURL;
+ NSURL *tokenURL;
+
+ // token exchange
+ NXOAuth2Connection *authConnection;
+ NXOAuth2AccessToken *accessToken;
+ NSMutableArray *waitingConnections; //for connections that are waiting for successful authorisation
+ NSInteger refreshConnectionDidRetryCount;
+
+ // delegates
+ NSObject<NXOAuth2ClientDelegate>* __unsafe_unretained delegate; // assigned
}
@property (nonatomic, readonly, getter = isAuthenticating) BOOL authenticating;
@@ -64,8 +64,8 @@ extern NSString * const NXOAuth2ClientConnectionContextTokenRefresh;
@property (nonatomic, copy) NSSet *desiredScope;
@property (nonatomic, copy) NSString *userAgent;
-@property (nonatomic, strong) NXOAuth2AccessToken *accessToken;
-@property (nonatomic, unsafe_unretained) NSObject<NXOAuth2ClientDelegate>* delegate;
+@property (nonatomic, strong) NXOAuth2AccessToken *accessToken;
+@property (nonatomic, unsafe_unretained) NSObject<NXOAuth2ClientDelegate>* delegate;
/*!
* If set to NO, the access token is not stored any keychain, will be removed if it was.
@@ -77,15 +77,15 @@ extern NSString * const NXOAuth2ClientConnectionContextTokenRefresh;
* Initializes the Client
*/
- (id)initWithClientID:(NSString *)clientId
- clientSecret:(NSString *)clientSecret
- authorizeURL:(NSURL *)authorizeURL
- tokenURL:(NSURL *)tokenURL
+ clientSecret:(NSString *)clientSecret
+ authorizeURL:(NSURL *)authorizeURL
+ tokenURL:(NSURL *)tokenURL
delegate:(NSObject<NXOAuth2ClientDelegate> *)delegate;
- (id)initWithClientID:(NSString *)clientId
- clientSecret:(NSString *)clientSecret
- authorizeURL:(NSURL *)authorizeURL
- tokenURL:(NSURL *)tokenURL
+ clientSecret:(NSString *)clientSecret
+ authorizeURL:(NSURL *)authorizeURL
+ tokenURL:(NSURL *)tokenURL
accessToken:(NXOAuth2AccessToken *)accessToken
persistent:(BOOL)shouldPersist
delegate:(NSObject<NXOAuth2ClientDelegate> *)delegate;
@@ -108,7 +108,7 @@ extern NSString * const NXOAuth2ClientConnectionContextTokenRefresh;
/*!
* Authenticate with username & password (User Credentials Flow)
*/
-- (void)authenticateWithUsername:(NSString *)username password:(NSString *)password;
+- (void)authenticateWithUsername:(NSString *)username password:(NSString *)password;
#pragma mark Public
View
390 Sources/OAuth2Client/NXOAuth2Client.m
@@ -4,10 +4,10 @@
//
// Created by Ullrich Schäfer on 27.08.10.
//
-// Copyright 2010 nxtbgthng. All rights reserved.
+// Copyright 2010 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
@@ -38,12 +38,12 @@ @implementation NXOAuth2Client
#pragma mark Lifecycle
- (id)initWithClientID:(NSString *)aClientId
- clientSecret:(NSString *)aClientSecret
- authorizeURL:(NSURL *)anAuthorizeURL
- tokenURL:(NSURL *)aTokenURL
+ clientSecret:(NSString *)aClientSecret
+ authorizeURL:(NSURL *)anAuthorizeURL
+ tokenURL:(NSURL *)aTokenURL
delegate:(NSObject<NXOAuth2ClientDelegate> *)aDelegate;
{
- return [self initWithClientID:aClientId
+ return [self initWithClientID:aClientId
clientSecret:aClientSecret
authorizeURL:anAuthorizeURL
tokenURL:aTokenURL
@@ -53,33 +53,33 @@ - (id)initWithClientID:(NSString *)aClientId
}
- (id)initWithClientID:(NSString *)aClientId
- clientSecret:(NSString *)aClientSecret
- authorizeURL:(NSURL *)anAuthorizeURL
- tokenURL:(NSURL *)aTokenURL
+ clientSecret:(NSString *)aClientSecret
+ authorizeURL:(NSURL *)anAuthorizeURL
+ tokenURL:(NSURL *)aTokenURL
accessToken:(NXOAuth2AccessToken *)anAccessToken
persistent:(BOOL)shouldPersist
delegate:(NSObject<NXOAuth2ClientDelegate> *)aDelegate;
{
NSAssert(aTokenURL != nil && anAuthorizeURL != nil, @"No token or no authorize URL");
- self = [super init];
- if (self) {
- refreshConnectionDidRetryCount = 0;
-
- clientId = [aClientId copy];
- clientSecret = [aClientSecret copy];
- authorizeURL = [anAuthorizeURL copy];
- tokenURL = [aTokenURL copy];
+ self = [super init];
+ if (self) {
+ refreshConnectionDidRetryCount = 0;
+
+ clientId = [aClientId copy];
+ clientSecret = [aClientSecret copy];
+ authorizeURL = [anAuthorizeURL copy];
+ tokenURL = [aTokenURL copy];
accessToken = anAccessToken;
self.persistent = shouldPersist;
- self.delegate = aDelegate;
- }
- return self;
+ self.delegate = aDelegate;
+ }
+ return self;
}
- (void)dealloc;
{
- [authConnection cancel];
+ [authConnection cancel];
}
@@ -91,51 +91,51 @@ - (void)dealloc;
- (void)setPersistent:(BOOL)shouldPersist;
{
- if (persistent == shouldPersist) return;
-
- if (shouldPersist && accessToken) {
- [self.accessToken storeInDefaultKeychainWithServiceProviderName:[tokenURL host]];
- }
-
- if (persistent && !shouldPersist) {
- [accessToken removeFromDefaultKeychainWithServiceProviderName:[tokenURL host]];
- }
-
- [self willChangeValueForKey:@"persistent"];
- persistent = shouldPersist;
- [self didChangeValueForKey:@"persistent"];
+ if (persistent == shouldPersist) return;
+
+ if (shouldPersist && accessToken) {
+ [self.accessToken storeInDefaultKeychainWithServiceProviderName:[tokenURL host]];
+ }
+
+ if (persistent && !shouldPersist) {
+ [accessToken removeFromDefaultKeychainWithServiceProviderName:[tokenURL host]];
+ }
+
+ [self willChangeValueForKey:@"persistent"];
+ persistent = shouldPersist;
+ [self didChangeValueForKey:@"persistent"];
}
- (NXOAuth2AccessToken *)accessToken;
{
- if (accessToken) return accessToken;
-
- if (persistent) {
- accessToken = [NXOAuth2AccessToken tokenFromDefaultKeychainWithServiceProviderName:[tokenURL host]];
- if (accessToken) {
+ if (accessToken) return accessToken;
+
+ if (persistent) {
+ accessToken = [NXOAuth2AccessToken tokenFromDefaultKeychainWithServiceProviderName:[tokenURL host]];
+ if (accessToken) {
if ([delegate respondsToSelector:@selector(oauthClientDidGetAccessToken:)]) {
[delegate oauthClientDidGetAccessToken:self];
}
- }
- return accessToken;
- } else {
- return nil;
- }
+ }
+ return accessToken;
+ } else {
+ return nil;
+ }
}
- (void)setAccessToken:(NXOAuth2AccessToken *)value;
{
- if (self.accessToken == value) return;
- BOOL authorisationStatusChanged = ((accessToken == nil) || (value == nil)); //They can't both be nil, see one line above. So they have to have changed from or to nil.
-
+ if (self.accessToken == value) return;
+ BOOL authorisationStatusChanged = ((accessToken == nil) || (value == nil)); //They can't both be nil, see one line above. So they have to have changed from or to nil.
+
if (!value) {
- [self.accessToken removeFromDefaultKeychainWithServiceProviderName:[tokenURL host]];
- }
-
- [self willChangeValueForKey:@"accessToken"];
- accessToken = value;
- [self didChangeValueForKey:@"accessToken"];
-
+ [self.accessToken removeFromDefaultKeychainWithServiceProviderName:[tokenURL host]];
+ }
+
+ [self willChangeValueForKey:@"accessToken"];
+ accessToken = value;
+ [self didChangeValueForKey:@"accessToken"];
+
if (persistent) {
[accessToken storeInDefaultKeychainWithServiceProviderName:[tokenURL host]];
}
@@ -162,77 +162,77 @@ - (void)setAccessToken:(NXOAuth2AccessToken *)value;
- (void)requestAccess;
{
- if (!self.accessToken) {
- [delegate oauthClientNeedsAuthentication:self];
- }
+ if (!self.accessToken) {
+ [delegate oauthClientNeedsAuthentication:self];
+ }
}
- (NSURL *)authorizationURLWithRedirectURL:(NSURL *)redirectURL;
{
- return [authorizeURL nxoauth2_URLByAddingParameters:[NSDictionary dictionaryWithObjectsAndKeys:
- @"code", @"response_type",
- clientId, @"client_id",
- [redirectURL absoluteString], @"redirect_uri",
- nil]];
+ return [authorizeURL nxoauth2_URLByAddingParameters:[NSDictionary dictionaryWithObjectsAndKeys:
+ @"code", @"response_type",
+ clientId, @"client_id",
+ [redirectURL absoluteString], @"redirect_uri",
+ nil]];
}
// Web Server Flow only
- (BOOL)openRedirectURL:(NSURL *)URL;
{
- NSString *accessGrant = [URL nxoauth2_valueForQueryParameterKey:@"code"];
- if (accessGrant) {
- [self requestTokenWithAuthGrant:accessGrant redirectURL:[URL nxoauth2_URLWithoutQueryString]];
- return YES;
- }
-
- NSString *errorString = [URL nxoauth2_valueForQueryParameterKey:@"error"];
- if (errorString) {
- NSInteger errorCode = 0;
- NSString *localizedError = nil;
-
- if ([errorString caseInsensitiveCompare:@"invalid_request"] == NSOrderedSame) {
- errorCode = NXOAuth2InvalidRequestErrorCode;
- localizedError = NSLocalizedString(@"Invalid request to OAuth2 Server", @"NXOAuth2InvalidRequestErrorCode description");
-
- } else if ([errorString caseInsensitiveCompare:@"invalid_client"] == NSOrderedSame) {
- errorCode = NXOAuth2InvalidClientErrorCode;
- localizedError = NSLocalizedString(@"Invalid OAuth2 Client", @"NXOAuth2InvalidClientErrorCode description");
-
- } else if ([errorString caseInsensitiveCompare:@"unauthorized_client"] == NSOrderedSame) {
- errorCode = NXOAuth2UnauthorizedClientErrorCode;
- localizedError = NSLocalizedString(@"Unauthorized Client", @"NXOAuth2UnauthorizedClientErrorCode description");
-
- } else if ([errorString caseInsensitiveCompare:@"redirect_uri_mismatch"] == NSOrderedSame) {
- errorCode = NXOAuth2RedirectURIMismatchErrorCode;
- localizedError = NSLocalizedString(@"Redirect URI mismatch", @"NXOAuth2RedirectURIMismatchErrorCode description");
-
- } else if ([errorString caseInsensitiveCompare:@"access_denied"] == NSOrderedSame) {
- errorCode = NXOAuth2AccessDeniedErrorCode;
- localizedError = NSLocalizedString(@"Access denied", @"NXOAuth2AccessDeniedErrorCode description");
-
- } else if ([errorString caseInsensitiveCompare:@"unsupported_response_type"] == NSOrderedSame) {
- errorCode = NXOAuth2UnsupportedResponseTypeErrorCode;
- localizedError = NSLocalizedString(@"Unsupported response type", @"NXOAuth2UnsupportedResponseTypeErrorCode description");
-
- } else if ([errorString caseInsensitiveCompare:@"invalid_scope"] == NSOrderedSame) {
- errorCode = NXOAuth2InvalidScopeErrorCode;
- localizedError = NSLocalizedString(@"Invalid scope", @"NXOAuth2InvalidScopeErrorCode description");
- }
-
- if (errorCode != 0) {
- NSDictionary *userInfo = nil;
- if (localizedError) {
- userInfo = [NSDictionary dictionaryWithObject:localizedError forKey:NSLocalizedDescriptionKey];
- }
+ NSString *accessGrant = [URL nxoauth2_valueForQueryParameterKey:@"code"];
+ if (accessGrant) {
+ [self requestTokenWithAuthGrant:accessGrant redirectURL:[URL nxoauth2_URLWithoutQueryString]];
+ return YES;
+ }
+
+ NSString *errorString = [URL nxoauth2_valueForQueryParameterKey:@"error"];
+ if (errorString) {
+ NSInteger errorCode = 0;
+ NSString *localizedError = nil;
+
+ if ([errorString caseInsensitiveCompare:@"invalid_request"] == NSOrderedSame) {
+ errorCode = NXOAuth2InvalidRequestErrorCode;
+ localizedError = NSLocalizedString(@"Invalid request to OAuth2 Server", @"NXOAuth2InvalidRequestErrorCode description");
+
+ } else if ([errorString caseInsensitiveCompare:@"invalid_client"] == NSOrderedSame) {
+ errorCode = NXOAuth2InvalidClientErrorCode;
+ localizedError = NSLocalizedString(@"Invalid OAuth2 Client", @"NXOAuth2InvalidClientErrorCode description");
+
+ } else if ([errorString caseInsensitiveCompare:@"unauthorized_client"] == NSOrderedSame) {
+ errorCode = NXOAuth2UnauthorizedClientErrorCode;
+ localizedError = NSLocalizedString(@"Unauthorized Client", @"NXOAuth2UnauthorizedClientErrorCode description");
+
+ } else if ([errorString caseInsensitiveCompare:@"redirect_uri_mismatch"] == NSOrderedSame) {
+ errorCode = NXOAuth2RedirectURIMismatchErrorCode;
+ localizedError = NSLocalizedString(@"Redirect URI mismatch", @"NXOAuth2RedirectURIMismatchErrorCode description");
+
+ } else if ([errorString caseInsensitiveCompare:@"access_denied"] == NSOrderedSame) {
+ errorCode = NXOAuth2AccessDeniedErrorCode;
+ localizedError = NSLocalizedString(@"Access denied", @"NXOAuth2AccessDeniedErrorCode description");
+
+ } else if ([errorString caseInsensitiveCompare:@"unsupported_response_type"] == NSOrderedSame) {
+ errorCode = NXOAuth2UnsupportedResponseTypeErrorCode;
+ localizedError = NSLocalizedString(@"Unsupported response type", @"NXOAuth2UnsupportedResponseTypeErrorCode description");
+
+ } else if ([errorString caseInsensitiveCompare:@"invalid_scope"] == NSOrderedSame) {
+ errorCode = NXOAuth2InvalidScopeErrorCode;
+ localizedError = NSLocalizedString(@"Invalid scope", @"NXOAuth2InvalidScopeErrorCode description");
+ }
+
+ if (errorCode != 0) {
+ NSDictionary *userInfo = nil;
+ if (localizedError) {
+ userInfo = [NSDictionary dictionaryWithObject:localizedError forKey:NSLocalizedDescriptionKey];
+ }
if ([delegate respondsToSelector:@selector(oauthClient:didFailToGetAccessTokenWithError:)]) {
[delegate oauthClient:self didFailToGetAccessTokenWithError:[NSError errorWithDomain:NXOAuth2ErrorDomain
code:errorCode
userInfo:userInfo]];
}
- }
- }
- return NO;
+ }
+ }
+ return NO;
}
#pragma mark Request Token
@@ -240,11 +240,11 @@ - (BOOL)openRedirectURL:(NSURL *)URL;
// Web Server Flow only
- (void)requestTokenWithAuthGrant:(NSString *)authGrant redirectURL:(NSURL *)redirectURL;
{
- NSAssert1(!authConnection, @"authConnection already running with: %@", authConnection);
-
- NSMutableURLRequest *tokenRequest = [NSMutableURLRequest requestWithURL:tokenURL];
- [tokenRequest setHTTPMethod:@"POST"];
- [authConnection cancel]; // just to be sure
+ NSAssert1(!authConnection, @"authConnection already running with: %@", authConnection);
+
+ NSMutableURLRequest *tokenRequest = [NSMutableURLRequest requestWithURL:tokenURL];
+ [tokenRequest setHTTPMethod:@"POST"];
+ [authConnection cancel]; // just to be sure
self.authenticating = YES;
@@ -258,22 +258,22 @@ - (void)requestTokenWithAuthGrant:(NSString *)authGrant redirectURL:(NSURL *)red
if (self.desiredScope) {
[parameters setObject:[[self.desiredScope allObjects] componentsJoinedByString:@" "] forKey:@"scope"];
}
- authConnection = [[NXOAuth2Connection alloc] initWithRequest:tokenRequest
- requestParameters:parameters
- oauthClient:self
- delegate:self];
- authConnection.context = NXOAuth2ClientConnectionContextTokenRequest;
+ authConnection = [[NXOAuth2Connection alloc] initWithRequest:tokenRequest
+ requestParameters:parameters
+ oauthClient:self
+ delegate:self];
+ authConnection.context = NXOAuth2ClientConnectionContextTokenRequest;
}
// User Password Flow Only
- (void)authenticateWithUsername:(NSString *)username password:(NSString *)password;
{
- NSAssert1(!authConnection, @"authConnection already running with: %@", authConnection);
-
- NSMutableURLRequest *tokenRequest = [NSMutableURLRequest requestWithURL:tokenURL];
- [tokenRequest setHTTPMethod:@"POST"];
- [authConnection cancel]; // just to be sure
+ NSAssert1(!authConnection, @"authConnection already running with: %@", authConnection);
+
+ NSMutableURLRequest *tokenRequest = [NSMutableURLRequest requestWithURL:tokenURL];
+ [tokenRequest setHTTPMethod:@"POST"];
+ [authConnection cancel]; // just to be sure
self.authenticating = YES;
@@ -287,11 +287,11 @@ - (void)authenticateWithUsername:(NSString *)username password:(NSString *)passw
if (self.desiredScope) {
[parameters setObject:[[self.desiredScope allObjects] componentsJoinedByString:@" "] forKey:@"scope"];
}
- authConnection = [[NXOAuth2Connection alloc] initWithRequest:tokenRequest
- requestParameters:parameters
- oauthClient:self
- delegate:self];
- authConnection.context = NXOAuth2ClientConnectionContextTokenRequest;
+ authConnection = [[NXOAuth2Connection alloc] initWithRequest:tokenRequest
+ requestParameters:parameters
+ oauthClient:self
+ delegate:self];
+ authConnection.context = NXOAuth2ClientConnectionContextTokenRequest;
}
@@ -299,20 +299,20 @@ - (void)authenticateWithUsername:(NSString *)username password:(NSString *)passw
- (void)refreshAccessToken;
{
- [self refreshAccessTokenAndRetryConnection:nil];
+ [self refreshAccessTokenAndRetryConnection:nil];
}
- (void)refreshAccessTokenAndRetryConnection:(NXOAuth2Connection *)retryConnection;
{
- if (retryConnection) {
- if (!waitingConnections) waitingConnections = [[NSMutableArray alloc] init];
- [waitingConnections addObject:retryConnection];
- }
- if (!authConnection) {
- NSAssert((accessToken.refreshToken != nil), @"invalid state");
- NSMutableURLRequest *tokenRequest = [NSMutableURLRequest requestWithURL:tokenURL];
- [tokenRequest setHTTPMethod:@"POST"];
- [authConnection cancel]; // not needed, but looks more clean to me :)
+ if (retryConnection) {
+ if (!waitingConnections) waitingConnections = [[NSMutableArray alloc] init];
+ [waitingConnections addObject:retryConnection];
+ }
+ if (!authConnection) {
+ NSAssert((accessToken.refreshToken != nil), @"invalid state");
+ NSMutableURLRequest *tokenRequest = [NSMutableURLRequest requestWithURL:tokenURL];
+ [tokenRequest setHTTPMethod:@"POST"];
+ [authConnection cancel]; // not needed, but looks more clean to me :)
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys:
@"refresh_token", @"grant_type",
@@ -323,17 +323,17 @@ - (void)refreshAccessTokenAndRetryConnection:(NXOAuth2Connection *)retryConnecti
if (self.desiredScope) {
[parameters setObject:[[self.desiredScope allObjects] componentsJoinedByString:@" "] forKey:@"scope"];
}
- authConnection = [[NXOAuth2Connection alloc] initWithRequest:tokenRequest
- requestParameters:parameters
- oauthClient:self
- delegate:self];
- authConnection.context = NXOAuth2ClientConnectionContextTokenRefresh;
- }
+ authConnection = [[NXOAuth2Connection alloc] initWithRequest:tokenRequest
+ requestParameters:parameters
+ oauthClient:self
+ delegate:self];
+ authConnection.context = NXOAuth2ClientConnectionContextTokenRefresh;
+ }
}
- (void)removeConnectionFromWaitingQueue:(NXOAuth2Connection *)aConnection;
{
- if (!aConnection) return;
+ if (!aConnection) return;
[waitingConnections removeObject:aConnection];
}
@@ -342,70 +342,70 @@ - (void)removeConnectionFromWaitingQueue:(NXOAuth2Connection *)aConnection;
- (void)oauthConnection:(NXOAuth2Connection *)connection didFinishWithData:(NSData *)data;
{
- if (connection == authConnection) {
+ if (connection == authConnection) {
self.authenticating = NO;
- NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
- NXOAuth2AccessToken *newToken = [NXOAuth2AccessToken tokenWithResponseBody:result];
- NSAssert(newToken != nil, @"invalid response?");
- self.accessToken = newToken;
-
- for (NXOAuth2Connection *retryConnection in waitingConnections) {
- [retryConnection retry];
- }
- [waitingConnections removeAllObjects];
-
- authConnection = nil;
-
- refreshConnectionDidRetryCount = 0; // reset
- }
+ NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
+ NXOAuth2AccessToken *newToken = [NXOAuth2AccessToken tokenWithResponseBody:result];
+ NSAssert(newToken != nil, @"invalid response?");
+ self.accessToken = newToken;
+
+ for (NXOAuth2Connection *retryConnection in waitingConnections) {
+ [retryConnection retry];
+ }
+ [waitingConnections removeAllObjects];
+
+ authConnection = nil;
+
+ refreshConnectionDidRetryCount = 0; // reset
+ }
}
- (void)oauthConnection:(NXOAuth2Connection *)connection didFailWithError:(NSError *)error;
{
- if (connection == authConnection) {
+ if (connection == authConnection) {
self.authenticating = NO;
- id context = connection.context;
- authConnection = nil;
-
- if ([context isEqualToString:NXOAuth2ClientConnectionContextTokenRefresh]
- && [[error domain] isEqualToString:NXOAuth2HTTPErrorDomain]
- && error.code >= 500 && error.code < 600
- && refreshConnectionDidRetryCount < 4) {
-
- // no token refresh because of a server issue. don't give up just yet.
- [self performSelector:@selector(refreshAccessToken) withObject:nil afterDelay:1];
- refreshConnectionDidRetryCount++;
-
- } else {
- if ([context isEqualToString:NXOAuth2ClientConnectionContextTokenRefresh]) {
- NSError *retryFailedError = [NSError errorWithDomain:NXOAuth2ErrorDomain
- code:NXOAuth2CouldNotRefreshTokenErrorCode
- userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
- NSLocalizedString(@"Access token could not be refreshed", @"NXOAuth2CouldNotRefreshTokenErrorCode description"), NSLocalizedDescriptionKey,
- nil]];
+ id context = connection.context;
+ authConnection = nil;
+
+ if ([context isEqualToString:NXOAuth2ClientConnectionContextTokenRefresh]
+ && [[error domain] isEqualToString:NXOAuth2HTTPErrorDomain]
+ && error.code >= 500 && error.code < 600
+ && refreshConnectionDidRetryCount < 4) {
+
+ // no token refresh because of a server issue. don't give up just yet.
+ [self performSelector:@selector(refreshAccessToken) withObject:nil afterDelay:1];
+ refreshConnectionDidRetryCount++;
+
+ } else {
+ if ([context isEqualToString:NXOAuth2ClientConnectionContextTokenRefresh]) {
+ NSError *retryFailedError = [NSError errorWithDomain:NXOAuth2ErrorDomain
+ code:NXOAuth2CouldNotRefreshTokenErrorCode
+ userInfo:[NSDictionary dictionaryWithObjectsAndKeys:
+ NSLocalizedString(@"Access token could not be refreshed", @"NXOAuth2CouldNotRefreshTokenErrorCode description"), NSLocalizedDescriptionKey,
+ nil]];
NSArray *failedConnections = [waitingConnections copy];
[waitingConnections removeAllObjects];
- for (NXOAuth2Connection *connection in failedConnections) {
- id<NXOAuth2ConnectionDelegate> connectionDelegate = connection.delegate;
+ for (NXOAuth2Connection *connection in failedConnections) {
+ id<NXOAuth2ConnectionDelegate> connectionDelegate = connection.delegate;
if ([connectionDelegate respondsToSelector:@selector(oauthConnection:didFailWithError:)]) {
- [connectionDelegate oauthConnection:connection didFailWithError:retryFailedError];
- }
+ [connectionDelegate oauthConnection:connection didFailWithError:retryFailedError];
+ }
}
- }
-
- if ([[error domain] isEqualToString:NXOAuth2HTTPErrorDomain]
- && error.code == 401) {
- self.accessToken = nil; // reset the token since it got invalid
- }
-
+ }
+
+ if ([[error domain] isEqualToString:NXOAuth2HTTPErrorDomain]
+ && error.code == 401) {
+ self.accessToken = nil; // reset the token since it got invalid
+ }
+
if ([delegate respondsToSelector:@selector(oauthClient:didFailToGetAccessTokenWithError:)]) {
[delegate oauthClient:self didFailToGetAccessTokenWithError:error];
}
- }
- }
+ }
+ }
}
@end
View
2  Sources/OAuth2Client/NXOAuth2ClientDelegate.h
@@ -7,7 +7,7 @@
// Copyright 2010 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
View
68 Sources/OAuth2Client/NXOAuth2Connection.h
@@ -4,10 +4,10 @@
//
// Created by Ullrich Schäfer on 27.08.10.
//
-// Copyright 2010 nxtbgthng. All rights reserved.
+// Copyright 2010 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
@@ -20,19 +20,19 @@
/*!
- * The connection
- *
- * NXOAuth2Connection is a wrapper around NXURLConnection.
- * It's main purpose is to simplify the delegates & to provide a context
- * ivar that can be used to put a connection object in a certain context.
- * The context may be compared to a tag.
- *
- * NXOAuth2Connection only provides asynchronous connections as synchronous
- * connections are strongly discouraged.
- *
- * The connection works together with the OAuth2 Client to sign a request
- * before sending it. If no client is passed in the connection will sent
- * unsigned requests.
+ * The connection
+ *
+ * NXOAuth2Connection is a wrapper around NXURLConnection.
+ * It's main purpose is to simplify the delegates & to provide a context
+ * ivar that can be used to put a connection object in a certain context.
+ * The context may be compared to a tag.
+ *
+ * NXOAuth2Connection only provides asynchronous connections as synchronous
+ * connections are strongly discouraged.
+ *
+ * The connection works together with the OAuth2 Client to sign a request
+ * before sending it. If no client is passed in the connection will sent
+ * unsigned requests.
*/
@@ -52,32 +52,32 @@ typedef void(^NXOAuth2ConnectionSendingProgressHandler)(unsigned long long bytes
@interface NXOAuth2Connection : NSObject {
@private
- NSURLConnection *connection;
- NSMutableURLRequest *request;
- NSURLResponse *response;
- NSDictionary *requestParameters;
-
- NSMutableData *data;
+ NSURLConnection *connection;
+ NSMutableURLRequest *request;
+ NSURLResponse *response;
+ NSDictionary *requestParameters;
+
+ NSMutableData *data;
BOOL savesData;
-
- id context;
- NSDictionary *userInfo;
-
- NXOAuth2Client *client;
-
- NSObject<NXOAuth2ConnectionDelegate> *__unsafe_unretained delegate; // assigned
+
+ id context;
+ NSDictionary *userInfo;
+
+ NXOAuth2Client *client;
+
+ NSObject<NXOAuth2ConnectionDelegate> *__unsafe_unretained delegate; // assigned
NXOAuth2ConnectionResponseHandler responseHandler;
NXOAuth2ConnectionSendingProgressHandler sendingProgressHandler;
-
- BOOL sendConnectionDidEndNotification;
+
+ BOOL sendConnectionDidEndNotification;
#if (NXOAuth2ConnectionDebug)
NSDate *startDate;
#endif
}
-@property (nonatomic, unsafe_unretained) NSObject<NXOAuth2ConnectionDelegate> *delegate;
+@property (nonatomic, unsafe_unretained) NSObject<NXOAuth2ConnectionDelegate> *delegate;
@property (nonatomic, strong, readonly) NSData *data;
@property (nonatomic, assign) BOOL savesData;
@property (nonatomic, assign, readonly) long long expectedContentLength;
@@ -94,9 +94,9 @@ sendingProgressHandler:(NXOAuth2ConnectionSendingProgressHandler)sendingProgress
responseHandler:(NXOAuth2ConnectionResponseHandler)responseHandler;
- (id)initWithRequest:(NSMutableURLRequest *)request
- requestParameters:(NSDictionary *)requestParameters
- oauthClient:(NXOAuth2Client *)client
- delegate:(NSObject<NXOAuth2ConnectionDelegate> *)delegate;
+ requestParameters:(NSDictionary *)requestParameters
+ oauthClient:(NXOAuth2Client *)client
+ delegate:(NSObject<NXOAuth2ConnectionDelegate> *)delegate;
- (void)cancel;
View
636 Sources/OAuth2Client/NXOAuth2Connection.m
@@ -4,10 +4,10 @@
//
// Created by Ullrich Schäfer on 27.08.10.
//
-// Copyright 2010 nxtbgthng. All rights reserved.
+// Copyright 2010 nxtbgthng. All rights reserved.
//
// Licenced under the new BSD-licence.
-// See README.md in this repository for
+// See README.md in this repository for
// the full licence.
//
@@ -35,11 +35,11 @@ - (NSURLConnection *)createConnection;
- (NSString *)descriptionForRequest:(NSURLRequest *)request;
- (void)applyParameters:(NSDictionary *)parameters onRequest:(NSMutableURLRequest *)request;
- (BOOL)trustsAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
- forHostname:(NSString *)hostname
- withTrustMode:(NXOAuth2TrustMode)trustMode;
+ forHostname:(NSString *)hostname
+ withTrustMode:(NXOAuth2TrustMode)trustMode;
- (BOOL)isServerCertificateForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
- andHostname:(NSString *)hostname
- matchingCertificate:(NSData *)derCertData;
+ andHostname:(NSString *)hostname
+ matchingCertificate:(NSData *)derCertData;
@property (nonatomic, unsafe_unretained, readonly) id<NXOAuth2TrustDelegate> trustDelegate;
@@ -65,33 +65,33 @@ - (id)initWithRequest:(NSMutableURLRequest *)aRequest
}
- (id)initWithRequest:(NSMutableURLRequest *)aRequest
- requestParameters:(NSDictionary *)someRequestParameters
- oauthClient:(NXOAuth2Client *)aClient
- delegate:(NSObject<NXOAuth2ConnectionDelegate> *)aDelegate;
+ requestParameters:(NSDictionary *)someRequestParameters
+ oauthClient:(NXOAuth2Client *)aClient
+ delegate:(NSObject<NXOAuth2ConnectionDelegate> *)aDelegate;
{
- self = [super init];
- if (self) {
- sendConnectionDidEndNotification = NO;
- delegate = aDelegate; // assign only
- client = aClient;
-
- request = [aRequest copy];
- requestParameters = [someRequestParameters copy];
- connection = [self createConnection];
+ self = [super init];
+ if (self) {
+ sendConnectionDidEndNotification = NO;
+ delegate = aDelegate; // assign only
+ client = aClient;
+
+ request = [aRequest copy];
+ requestParameters = [someRequestParameters copy];
+ connection = [self createConnection];
savesData = YES;
- }
- return self;
+ }
+ return self;
}
- (void)dealloc;
{
- if (sendConnectionDidEndNotification) [[NSNotificationCenter defaultCenter] postNotificationName:NXOAuth2ConnectionDidEndNotification object:self];
- sendConnectionDidEndNotification = NO;
+ if (sendConnectionDidEndNotification) [[NSNotificationCenter defaultCenter] postNotificationName:NXOAuth2ConnectionDidEndNotification object:self];
+ sendConnectionDidEndNotification = NO;
- [connection cancel];
+ [connection cancel];
#if (NXOAuth2ConnectionDebug)
- [startDate release];
+ [startDate release];
#endif
}
@@ -109,20 +109,20 @@ - (void)dealloc;
- (id<NXOAuth2TrustDelegate>)trustDelegate;
{
// if a client is set and implemnts the trustModeForHostname: it is preferred
- // in making trust desicions.
- // The second choice
+ // in making trust desicions.
+ // The second choice
if (client && [client.delegate conformsToProtocol:@protocol(NXOAuth2TrustDelegate)]) {
- return (id<NXOAuth2TrustDelegate>)client.delegate;
+ return (id<NXOAuth2TrustDelegate>)client.delegate;
} else if ([delegate conformsToProtocol:@protocol(NXOAuth2TrustDelegate)]) {
- return (id<NXOAuth2TrustDelegate>)delegate;
+ return (id<NXOAuth2TrustDelegate>)delegate;
}
- return nil;
+ return nil;
}
- (NSInteger)statusCode;
{
- if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
- NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
+ if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
+ NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
return httpResponse.statusCode;
}
return 0;
@@ -130,30 +130,30 @@ - (NSInteger)statusCode;
- (long long)expectedContentLength;
{
- return response.expectedContentLength;
+ return response.expectedContentLength;
}
- (NSString *)description;
{
- return [NSString stringWithFormat:@"NXOAuth2Connection <%@>", request.URL];
+ return [NSString stringWithFormat:@"NXOAuth2Connection <%@>", request.URL];
}
#pragma mark Public
- (void)cancel;
{
- if (sendConnectionDidEndNotification) [[NSNotificationCenter defaultCenter] postNotificationName:NXOAuth2ConnectionDidEndNotification object:self];
- sendConnectionDidEndNotification = NO;
-
- [connection cancel];
- [client removeConnectionFromWaitingQueue:self];
+ if (sendConnectionDidEndNotification) [[NSNotificationCenter defaultCenter] postNotificationName:NXOAuth2ConnectionDidEndNotification object:self];
+ sendConnectionDidEndNotification = NO;
+
+ [connection cancel];
+ [client removeConnectionFromWaitingQueue:self];
}
- (void)retry;
{
- response = nil;
- [connection cancel];
- connection = [self createConnection];
+ response = nil;
+ [connection cancel];
+ connection = [self createConnection];
}
@@ -161,111 +161,111 @@ - (void)retry;
- (NSURLConnection *)createConnection;
{
- // if the request is a token refresh request don't sign it and don't check for the expiration of the token (we know that already)
- NSString *oauthAuthorizationHeader = nil;
- if (client.accessToken &&
- ![[requestParameters objectForKey:@"grant_type"] isEqualToString:@"refresh_token"]) {
-
- // if token is expired don't bother starting this connection.
- NSDate *tenSecondsAgo = [NSDate dateWithTimeIntervalSinceNow:(-10)];
- NSDate *tokenExpiresAt = client.accessToken.expiresAt;
- if ([tenSecondsAgo earlierDate:tokenExpiresAt] == tokenExpiresAt) {
- [self cancel];
- [client refreshAccessTokenAndRetryConnection:self];
- return nil;
- }
-
- oauthAuthorizationHeader = [NSString stringWithFormat:@"OAuth %@", client.accessToken.accessToken];
- }
-
- NSMutableURLRequest *startRequest = [request mutableCopy];
- [self applyParameters:requestParameters onRequest:startRequest];
-
- if (oauthAuthorizationHeader) {
- [startRequest setValue:oauthAuthorizationHeader forHTTPHeaderField:@"Authorization"];
- }
-
- if (client.userAgent && ![startRequest valueForHTTPHeaderField:@"User-Agent"]) {
- [startRequest setValue:client.userAgent forHTTPHeaderField:@"User-Agent"];
- }
-
- NSURLConnection *aConnection = [[NSURLConnection alloc] initWithRequest:startRequest delegate:self startImmediately:NO]; // don't start yet
- [aConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; // let's first schedule it in the current runloop. (see http://github.com/soundcloud/cocoa-api-wrapper/issues#issue/2 )
- [aConnection start]; // now start
+ // if the request is a token refresh request don't sign it and don't check for the expiration of the token (we know that already)
+ NSString *oauthAuthorizationHeader = nil;
+ if (client.accessToken &&
+ ![[requestParameters objectForKey:@"grant_type"] isEqualToString:@"refresh_token"]) {
+
+ // if token is expired don't bother starting this connection.
+ NSDate *tenSecondsAgo = [NSDate dateWithTimeIntervalSinceNow:(-10)];
+ NSDate *tokenExpiresAt = client.accessToken.expiresAt;
+ if ([tenSecondsAgo earlierDate:tokenExpiresAt] == tokenExpiresAt) {
+ [self cancel];
+ [client refreshAccessTokenAndRetryConnection:self];
+ return nil;
+ }
+
+ oauthAuthorizationHeader = [NSString stringWithFormat:@"OAuth %@", client.accessToken.accessToken];
+ }
+
+ NSMutableURLRequest *startRequest = [request mutableCopy];
+ [self applyParameters:requestParameters onRequest:startRequest];
+
+ if (oauthAuthorizationHeader) {
+ [startRequest setValue:oauthAuthorizationHeader forHTTPHeaderField:@"Authorization"];
+ }
+
+ if (client.userAgent && ![startRequest valueForHTTPHeaderField:@"User-Agent"]) {
+ [startRequest setValue:client.userAgent forHTTPHeaderField:@"User-Agent"];
+ }
+
+ NSURLConnection *aConnection = [[NSURLConnection alloc] initWithRequest:startRequest delegate:self startImmediately:NO]; // don't start yet
+ [aConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; // let's first schedule it in the current runloop. (see http://github.com/soundcloud/cocoa-api-wrapper/issues#issue/2 )
+ [aConnection start]; // now start
#if (NXOAuth2ConnectionDebug)
[startDate release]; startDate = [[NSDate alloc] init];
#endif
-
- if (!sendConnectionDidEndNotification) [[NSNotificationCenter defaultCenter] postNotificationName:NXOAuth2ConnectionDidStartNotification object:self];
- sendConnectionDidEndNotification = YES;
-
- return aConnection;
+
+ if (!sendConnectionDidEndNotification) [[NSNotificationCenter defaultCenter] postNotificationName:NXOAuth2ConnectionDidStartNotification object:self];
+ sendConnectionDidEndNotification = YES;
+
+ return aConnection;
}
- (NSString *)descriptionForRequest:(NSURLRequest *)aRequest;
{
- NSString *range = [aRequest valueForHTTPHeaderField:@"Range"];
- if (!range) {
- return aRequest.URL.absoluteString;
- }
- return [NSString stringWithFormat:@"%@ [%@]", aRequest.URL.absoluteString, range];
+ NSString *range = [aRequest valueForHTTPHeaderField:@"Range"];
+ if (!range) {
+ return aRequest.URL.absoluteString;
+ }
+ return [NSString stringWithFormat:@"%@ [%@]", aRequest.URL.absoluteString, range];
}
- (void)applyParameters:(NSDictionary *)parameters onRequest:(NSMutableURLRequest *)aRequest;
{
- if (!parameters) return;
-
- NSString *httpMethod = [aRequest HTTPMethod];
- if ([httpMethod caseInsensitiveCompare:@"POST"] != NSOrderedSame
- && [httpMethod caseInsensitiveCompare:@"PUT"] != NSOrderedSame) {
- aRequest.URL = [aRequest.URL nxoauth2_URLByAddingParameters:parameters];
- } else {
- NSInputStream *postBodyStream = [[NXOAuth2PostBodyStream alloc] initWithParameters:parameters];
-
- NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", [(NXOAuth2PostBodyStream *)postBodyStream boundary]];
- NSString *contentLength = [NSString stringWithFormat:@"%lld", [(NXOAuth2PostBodyStream *)postBodyStream length]];
- [aRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];
- [aRequest setValue:contentLength forHTTPHeaderField:@"Content-Length"];
-
- [aRequest setHTTPBodyStream:postBodyStream];
- }
+ if (!parameters) return;
+
+ NSString *httpMethod = [aRequest HTTPMethod];
+ if ([httpMethod caseInsensitiveCompare:@"POST"] != NSOrderedSame
+ && [httpMethod caseInsensitiveCompare:@"PUT"] != NSOrderedSame) {
+ aRequest.URL = [aRequest.URL nxoauth2_URLByAddingParameters:parameters];
+ } else {
+ NSInputStream *postBodyStream = [[NXOAuth2PostBodyStream alloc] initWithParameters:parameters];
+
+ NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", [(NXOAuth2PostBodyStream *)postBodyStream boundary]];
+ NSString *contentLength = [NSString stringWithFormat:@"%lld", [(NXOAuth2PostBodyStream *)postBodyStream length]];
+ [aRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];
+ [aRequest setValue:contentLength forHTTPHeaderField:@"Content-Length"];
+
+ [aRequest setHTTPBodyStream:postBodyStream];
+ }
}
- (BOOL)trustsAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
- forHostname:(NSString *)hostname
- withTrustMode:(NXOAuth2TrustMode)trustMode;
+ forHostname:(NSString *)hostname
+ withTrustMode:(NXOAuth2TrustMode)trustMode;
{
- if (trustMode & NXOAuth2TrustModeAnyCertificate) {
- return YES;
- }
-
- if (trustMode & NXOAuth2TrustModeSystem) {
- SecTrustResultType trustEvalResult = kSecTrustResultInvalid;
- OSStatus ossTrust = SecTrustEvaluate(challenge.protectionSpace.serverTrust, &trustEvalResult);
-
- if (ossTrust != errSecSuccess) {
- NSLog(@"Trust evaluation failed for domain %@. Rejecting cert.", hostname);
- return NO;
- }
-
- // TODO: The result might also be kSecTrustResultConfirm
- // But to be safe we ignore this for now
- // if it is kSecTrustResultConfirm, there could be another delegate
- // method that allows to show a delegate UI
- if (trustEvalResult == kSecTrustResultProceed ||
- trustEvalResult == kSecTrustResultUnspecified) {
- return YES;
- }
- }
-
-
- if (trustMode & NXOAuth2TrustModeSpecificCertificate) {
- NSAssert([self.trustDelegate respondsToSelector:@selector(connection:trustedCertificatesForHostname:)],
- @"For NXOAuth2TrustModeSpecificCertificate the delegate needs to implement oauthConnection:trustedCertificatesDERDataForHostname:");
- NSArray *trustedCerts = [self.trustDelegate connection:self trustedCertificatesForHostname:hostname];
-
+ if (trustMode & NXOAuth2TrustModeAnyCertificate) {
+ return YES;
+ }
+
+ if (trustMode & NXOAuth2TrustModeSystem) {
+ SecTrustResultType trustEvalResult = kSecTrustResultInvalid;
+ OSStatus ossTrust = SecTrustEvaluate(challenge.protectionSpace.serverTrust, &trustEvalResult);
+
+ if (ossTrust != errSecSuccess) {
+ NSLog(@"Trust evaluation failed for domain %@. Rejecting cert.