This repository was archived by the owner on Jan 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 337
Expand file tree
/
Copy pathAFOAuth2Manager.m
More file actions
395 lines (312 loc) · 16.3 KB
/
AFOAuth2Manager.m
File metadata and controls
395 lines (312 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// AFOAuth2Manager.m
//
// Copyright (c) 2012-2014 AFNetworking (http://afnetworking.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <Security/Security.h>
#import "AFOAuth2Manager.h"
NSString * const AFOAuth2ErrorDomain = @"com.alamofire.networking.oauth2.error";
NSString * const kAFOAuthCodeGrantType = @"authorization_code";
NSString * const kAFOAuthClientCredentialsGrantType = @"client_credentials";
NSString * const kAFOAuthPasswordCredentialsGrantType = @"password";
NSString * const kAFOAuthRefreshGrantType = @"refresh_token";
NSString * const kAFOAuth2CredentialServiceName = @"AFOAuthCredentialService";
static NSDictionary * AFKeychainQueryDictionaryWithIdentifier(NSString *identifier) {
NSCParameterAssert(identifier);
return @{
(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrService: kAFOAuth2CredentialServiceName,
(__bridge id)kSecAttrAccount: identifier
};
}
// See: http://tools.ietf.org/html/rfc6749#section-5.2
static NSError * AFErrorFromRFC6749Section5_2Error(id object) {
if (![object valueForKey:@"error"] || [[object valueForKey:@"error"] isEqual:[NSNull null]]) {
return nil;
}
NSMutableDictionary *mutableUserInfo = [NSMutableDictionary dictionary];
NSString *description = nil;
if ([object valueForKey:@"error_description"]) {
description = [object valueForKey:@"error_description"];
} else {
if ([[object valueForKey:@"error"] isEqualToString:@"invalid_request"]) {
description = NSLocalizedStringFromTable(@"The request is missing a required parameter, includes an unsupported parameter value (other than grant type), repeats a parameter, includes multiple credentials, utilizes more than one mechanism for authenticating the client, or is otherwise malformed.", @"AFOAuth2Manager", @"invalid_request");
} else if ([[object valueForKey:@"error"] isEqualToString:@"invalid_client"]) {
description = NSLocalizedStringFromTable(@"Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method). The authorization server MAY return an HTTP 401 (Unauthorized) status code to indicate which HTTP authentication schemes are supported. If the client attempted to authenticate via the \"Authorization\" request header field, the authorization server MUST respond with an HTTP 401 (Unauthorized) status code and include the \"WWW-Authenticate\" response header field matching the authentication scheme used by the client.", @"AFOAuth2Manager", @"invalid_request");
} else if ([[object valueForKey:@"error"] isEqualToString:@"invalid_grant"]) {
description = NSLocalizedStringFromTable(@"The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client.", @"AFOAuth2Manager", @"invalid_request");
} else if ([[object valueForKey:@"error"] isEqualToString:@"unauthorized_client"]) {
description = NSLocalizedStringFromTable(@"The authenticated client is not authorized to use this authorization grant type.", @"AFOAuth2Manager", @"invalid_request");
} else if ([[object valueForKey:@"error"] isEqualToString:@"unsupported_grant_type"]) {
description = NSLocalizedStringFromTable(@"The authorization grant type is not supported by the authorization server.", @"AFOAuth2Manager", @"invalid_request");
}
}
if (description) {
mutableUserInfo[NSLocalizedDescriptionKey] = description;
}
if ([object valueForKey:@"error_uri"]) {
mutableUserInfo[NSLocalizedRecoverySuggestionErrorKey] = [object valueForKey:@"error_uri"];
}
return [NSError errorWithDomain:AFOAuth2ErrorDomain code:-1 userInfo:mutableUserInfo];
}
#pragma mark -
@interface AFOAuth2Manager ()
@property (readwrite, nonatomic, copy) NSString *serviceProviderIdentifier;
@property (readwrite, nonatomic, copy) NSString *clientID;
@property (readwrite, nonatomic, copy) NSString *secret;
@end
@implementation AFOAuth2Manager
+ (instancetype)clientWithBaseURL:(NSURL *)url
clientID:(NSString *)clientID
secret:(NSString *)secret
{
return [[self alloc] initWithBaseURL:url clientID:clientID secret:secret];
}
- (id)initWithBaseURL:(NSURL *)url
clientID:(NSString *)clientID
secret:(NSString *)secret
{
NSParameterAssert(clientID);
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
self.serviceProviderIdentifier = [self.baseURL host];
self.clientID = clientID;
self.secret = secret;
[self.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
return self;
}
#pragma mark -
- (AFHTTPRequestOperation *)authenticateUsingOAuthWithURLString:(NSString *)URLString
username:(NSString *)username
password:(NSString *)password
scope:(NSString *)scope
success:(void (^)(AFOAuthCredential *credential))success
failure:(void (^)(NSError *error))failure
{
NSParameterAssert(username);
NSParameterAssert(password);
NSParameterAssert(scope);
NSDictionary *parameters = @{
@"grant_type": kAFOAuthPasswordCredentialsGrantType,
@"username": username,
@"password": password,
@"scope": scope
};
return [self authenticateUsingOAuthWithURLString:URLString parameters:parameters success:success failure:failure];
}
- (AFHTTPRequestOperation *)authenticateUsingOAuthWithURLString:(NSString *)URLString
scope:(NSString *)scope
success:(void (^)(AFOAuthCredential *credential))success
failure:(void (^)(NSError *error))failure
{
NSParameterAssert(scope);
NSDictionary *parameters = @{
@"grant_type": kAFOAuthClientCredentialsGrantType,
@"scope": scope
};
return [self authenticateUsingOAuthWithURLString:URLString parameters:parameters success:success failure:failure];
}
- (AFHTTPRequestOperation *)authenticateUsingOAuthWithURLString:(NSString *)URLString
refreshToken:(NSString *)refreshToken
success:(void (^)(AFOAuthCredential *credential))success
failure:(void (^)(NSError *error))failure
{
NSParameterAssert(refreshToken);
NSDictionary *parameters = @{
@"grant_type": kAFOAuthRefreshGrantType,
@"refresh_token": refreshToken
};
return [self authenticateUsingOAuthWithURLString:URLString parameters:parameters success:success failure:failure];
}
- (AFHTTPRequestOperation *)authenticateUsingOAuthWithURLString:(NSString *)URLString
code:(NSString *)code
redirectURI:(NSString *)uri
success:(void (^)(AFOAuthCredential *credential))success
failure:(void (^)(NSError *error))failure
{
NSParameterAssert(code);
NSParameterAssert(uri);
NSDictionary *parameters = @{
@"grant_type": kAFOAuthCodeGrantType,
@"code": code,
@"redirect_uri": uri
};
return [self authenticateUsingOAuthWithURLString:URLString parameters:parameters success:success failure:failure];
}
- (AFHTTPRequestOperation *)authenticateUsingOAuthWithURLString:(NSString *)URLString
parameters:(NSDictionary *)parameters
success:(void (^)(AFOAuthCredential *credential))success
failure:(void (^)(NSError *error))failure
{
NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionaryWithDictionary:parameters];
mutableParameters[@"client_id"] = self.clientID;
mutableParameters[@"client_secret"] = self.secret;
parameters = [NSDictionary dictionaryWithDictionary:mutableParameters];
AFHTTPRequestOperation *requestOperation = [self POST:URLString parameters:parameters success:^(__unused AFHTTPRequestOperation *operation, id responseObject) {
if (!responseObject) {
if (failure) {
failure(nil);
}
return;
}
if ([responseObject valueForKey:@"error"]) {
if (failure) {
failure(AFErrorFromRFC6749Section5_2Error(responseObject));
}
return;
}
NSString *refreshToken = [responseObject valueForKey:@"refresh_token"];
if (!refreshToken || [refreshToken isEqual:[NSNull null]]) {
refreshToken = [parameters valueForKey:@"refresh_token"];
}
AFOAuthCredential *credential = [AFOAuthCredential credentialWithOAuthToken:[responseObject valueForKey:@"access_token"] tokenType:[responseObject valueForKey:@"token_type"]];
NSDate *expireDate = [NSDate distantFuture];
id expiresIn = [responseObject valueForKey:@"expires_in"];
if (expiresIn && ![expiresIn isEqual:[NSNull null]]) {
expireDate = [NSDate dateWithTimeIntervalSinceNow:[expiresIn doubleValue]];
}
if (refreshToken && expireDate) {
[credential setRefreshToken:refreshToken expiration:expireDate];
}
if (success) {
success(credential);
}
} failure:^(__unused AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(error);
}
}];
return requestOperation;
}
@end
#pragma mark -
@interface AFOAuthCredential ()
@property (readwrite, nonatomic, copy) NSString *accessToken;
@property (readwrite, nonatomic, copy) NSString *tokenType;
@property (readwrite, nonatomic, copy) NSString *refreshToken;
@property (readwrite, nonatomic, copy) NSDate *expiration;
@end
@implementation AFOAuthCredential
@dynamic expired;
#pragma mark -
+ (instancetype)credentialWithOAuthToken:(NSString *)token
tokenType:(NSString *)type
{
return [[self alloc] initWithOAuthToken:token tokenType:type];
}
- (id)initWithOAuthToken:(NSString *)token
tokenType:(NSString *)type
{
self = [super init];
if (!self) {
return nil;
}
self.accessToken = token;
self.tokenType = type;
return self;
}
- (NSString *)description {
return [NSString stringWithFormat:@"<%@ accessToken:\"%@\" tokenType:\"%@\" refreshToken:\"%@\" expiration:\"%@\">", [self class], self.accessToken, self.tokenType, self.refreshToken, self.expiration];
}
- (void)setRefreshToken:(NSString *)refreshToken
expiration:(NSDate *)expiration
{
NSParameterAssert(expiration);
self.refreshToken = refreshToken;
self.expiration = expiration;
}
- (BOOL)isExpired {
return [self.expiration compare:[NSDate date]] == NSOrderedAscending;
}
#pragma mark Keychain
+ (BOOL)storeCredential:(AFOAuthCredential *)credential
withIdentifier:(NSString *)identifier
{
id securityAccessibility = nil;
#if (defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 43000) || (defined(__MAC_OS_X_VERSION_MAX_ALLOWED) && __MAC_OS_X_VERSION_MAX_ALLOWED >= 1090)
if (kSecAttrAccessibleWhenUnlocked != NULL) {
securityAccessibility = (__bridge id)kSecAttrAccessibleWhenUnlocked;
}
#endif
return [[self class] storeCredential:credential withIdentifier:identifier withAccessibility:securityAccessibility];
}
+ (BOOL)storeCredential:(AFOAuthCredential *)credential
withIdentifier:(NSString *)identifier
withAccessibility:(id)securityAccessibility
{
NSMutableDictionary *queryDictionary = [AFKeychainQueryDictionaryWithIdentifier(identifier) mutableCopy];
if (!credential) {
return [self deleteCredentialWithIdentifier:identifier];
}
NSMutableDictionary *updateDictionary = [NSMutableDictionary dictionary];
updateDictionary[(__bridge id)kSecValueData] = [NSKeyedArchiver archivedDataWithRootObject:credential];
if (securityAccessibility) {
updateDictionary[(__bridge id)kSecAttrAccessible] = securityAccessibility;
}
OSStatus status;
BOOL exists = ([self retrieveCredentialWithIdentifier:identifier] != nil);
if (exists) {
status = SecItemUpdate((__bridge CFDictionaryRef)queryDictionary, (__bridge CFDictionaryRef)updateDictionary);
} else {
[queryDictionary addEntriesFromDictionary:updateDictionary];
status = SecItemAdd((__bridge CFDictionaryRef)queryDictionary, NULL);
}
if (status != errSecSuccess) {
NSLog(@"Unable to %@ credential with identifier \"%@\" (Error %li)", exists ? @"update" : @"add", identifier, (long int)status);
}
return (status == errSecSuccess);
}
+ (BOOL)deleteCredentialWithIdentifier:(NSString *)identifier {
NSMutableDictionary *queryDictionary = [AFKeychainQueryDictionaryWithIdentifier(identifier) mutableCopy];
OSStatus status = SecItemDelete((__bridge CFDictionaryRef)queryDictionary);
if (status != errSecSuccess) {
NSLog(@"Unable to delete credential with identifier \"%@\" (Error %li)", identifier, (long int)status);
}
return (status == errSecSuccess);
}
+ (AFOAuthCredential *)retrieveCredentialWithIdentifier:(NSString *)identifier {
NSMutableDictionary *queryDictionary = [AFKeychainQueryDictionaryWithIdentifier(identifier) mutableCopy];
queryDictionary[(__bridge id)kSecReturnData] = (__bridge id)kCFBooleanTrue;
queryDictionary[(__bridge id)kSecMatchLimit] = (__bridge id)kSecMatchLimitOne;
CFDataRef result = nil;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)queryDictionary, (CFTypeRef *)&result);
if (status != errSecSuccess) {
NSLog(@"Unable to fetch credential with identifier \"%@\" (Error %li)", identifier, (long int)status);
return nil;
}
return [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge_transfer NSData *)result];
}
#pragma mark - NSCoding
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
self.accessToken = [decoder decodeObjectForKey:NSStringFromSelector(@selector(accessToken))];
self.tokenType = [decoder decodeObjectForKey:NSStringFromSelector(@selector(tokenType))];
self.refreshToken = [decoder decodeObjectForKey:NSStringFromSelector(@selector(refreshToken))];
self.expiration = [decoder decodeObjectForKey:NSStringFromSelector(@selector(expiration))];
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.accessToken forKey:NSStringFromSelector(@selector(accessToken))];
[encoder encodeObject:self.tokenType forKey:NSStringFromSelector(@selector(tokenType))];
[encoder encodeObject:self.refreshToken forKey:NSStringFromSelector(@selector(refreshToken))];
[encoder encodeObject:self.expiration forKey:NSStringFromSelector(@selector(expiration))];
}
@end