PageRenderTime 30ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/core/externals/update-engine/externals/gdata-objectivec-client/Source/OAuth2/GTMOAuth2Authentication.h

http://macfuse.googlecode.com/
C Header | 350 lines | 139 code | 75 blank | 136 comment | 1 complexity | 5fb14c40479581ab3e723bdf0b426933 MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause, GPL-2.0
  1. /* Copyright (c) 2011 Google Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. #if GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES
  16. // This class implements the OAuth 2 protocol for authorizing requests.
  17. // http://tools.ietf.org/html/draft-ietf-oauth-v2
  18. #import <Foundation/Foundation.h>
  19. // GTMHTTPFetcher.h brings in GTLDefines/GDataDefines
  20. #import "GTMHTTPFetcher.h"
  21. // Until all OAuth 2 providers are up to the same spec, we'll provide a crude
  22. // way here to override the "Bearer" string in the Authorization header
  23. #ifndef GTM_OAUTH2_BEARER
  24. #define GTM_OAUTH2_BEARER "Bearer"
  25. #endif
  26. #ifdef __cplusplus
  27. extern "C" {
  28. #endif
  29. // Service provider name allows stored authorization to be associated with
  30. // the authorizing service
  31. extern NSString *const kGTMOAuth2ServiceProviderGoogle;
  32. //
  33. // GTMOAuth2SignIn constants, included here for use by clients
  34. //
  35. extern NSString *const kGTMOAuth2ErrorDomain;
  36. // Error userInfo keys
  37. extern NSString *const kGTMOAuth2ErrorMessageKey;
  38. extern NSString *const kGTMOAuth2ErrorRequestKey;
  39. extern NSString *const kGTMOAuth2ErrorJSONKey;
  40. enum {
  41. // Error code indicating that the window was prematurely closed
  42. kGTMOAuth2ErrorWindowClosed = -1000,
  43. kGTMOAuth2ErrorAuthorizationFailed = -1001,
  44. kGTMOAuth2ErrorTokenExpired = -1002,
  45. kGTMOAuth2ErrorTokenUnavailable = -1003,
  46. kGTMOAuth2ErrorUnauthorizableRequest = -1004
  47. };
  48. // Notifications for token fetches
  49. extern NSString *const kGTMOAuth2FetchStarted;
  50. extern NSString *const kGTMOAuth2FetchStopped;
  51. extern NSString *const kGTMOAuth2FetcherKey;
  52. extern NSString *const kGTMOAuth2FetchTypeKey;
  53. extern NSString *const kGTMOAuth2FetchTypeToken;
  54. extern NSString *const kGTMOAuth2FetchTypeRefresh;
  55. extern NSString *const kGTMOAuth2FetchTypeAssertion;
  56. extern NSString *const kGTMOAuth2FetchTypeUserInfo;
  57. // Token-issuance errors
  58. extern NSString *const kGTMOAuth2ErrorKey;
  59. extern NSString *const kGTMOAuth2ErrorObjectKey;
  60. extern NSString *const kGTMOAuth2ErrorInvalidRequest;
  61. extern NSString *const kGTMOAuth2ErrorInvalidClient;
  62. extern NSString *const kGTMOAuth2ErrorInvalidGrant;
  63. extern NSString *const kGTMOAuth2ErrorUnauthorizedClient;
  64. extern NSString *const kGTMOAuth2ErrorUnsupportedGrantType;
  65. extern NSString *const kGTMOAuth2ErrorInvalidScope;
  66. // Notification that sign-in has completed, and token fetches will begin (useful
  67. // for displaying interstitial messages after the window has closed)
  68. extern NSString *const kGTMOAuth2UserSignedIn;
  69. // Notification for token changes
  70. extern NSString *const kGTMOAuth2AccessTokenRefreshed;
  71. extern NSString *const kGTMOAuth2RefreshTokenChanged;
  72. extern NSString *const kGTMOAuth2AccessTokenRefreshFailed;
  73. // Notification for WebView loading
  74. extern NSString *const kGTMOAuth2WebViewStartedLoading;
  75. extern NSString *const kGTMOAuth2WebViewStoppedLoading;
  76. extern NSString *const kGTMOAuth2WebViewKey;
  77. extern NSString *const kGTMOAuth2WebViewStopKindKey;
  78. extern NSString *const kGTMOAuth2WebViewFinished;
  79. extern NSString *const kGTMOAuth2WebViewFailed;
  80. extern NSString *const kGTMOAuth2WebViewCancelled;
  81. // Notification for network loss during html sign-in display
  82. extern NSString *const kGTMOAuth2NetworkLost;
  83. extern NSString *const kGTMOAuth2NetworkFound;
  84. #ifdef __cplusplus
  85. }
  86. #endif
  87. @interface GTMOAuth2Authentication : NSObject <GTMFetcherAuthorizationProtocol> {
  88. @private
  89. NSString *clientID_;
  90. NSString *clientSecret_;
  91. NSString *redirectURI_;
  92. NSMutableDictionary *parameters_;
  93. // authorization parameters
  94. NSURL *tokenURL_;
  95. NSDate *expirationDate_;
  96. NSString *authorizationTokenKey_;
  97. NSDictionary *additionalTokenRequestParameters_;
  98. NSDictionary *additionalGrantTypeRequestParameters_;
  99. // queue of requests for authorization waiting for a valid access token
  100. GTMHTTPFetcher *refreshFetcher_;
  101. NSMutableArray *authorizationQueue_;
  102. id <GTMHTTPFetcherServiceProtocol> fetcherService_; // WEAK
  103. Class parserClass_;
  104. BOOL shouldAuthorizeAllRequests_;
  105. // arbitrary data retained for the user
  106. id userData_;
  107. NSMutableDictionary *properties_;
  108. }
  109. // OAuth2 standard protocol parameters
  110. //
  111. // These should be the plain strings; any needed escaping will be provided by
  112. // the library.
  113. // Request properties
  114. @property (copy) NSString *clientID;
  115. @property (copy) NSString *clientSecret;
  116. @property (copy) NSString *redirectURI;
  117. @property (retain) NSString *scope;
  118. @property (retain) NSString *tokenType;
  119. @property (retain) NSString *assertion;
  120. @property (retain) NSString *refreshScope;
  121. // Apps may optionally add parameters here to be provided to the token
  122. // endpoint on token requests and refreshes.
  123. @property (retain) NSDictionary *additionalTokenRequestParameters;
  124. // Apps may optionally add parameters here to be provided to the token
  125. // endpoint on specific token requests and refreshes, keyed by the grant_type.
  126. // For example, if a different "type" parameter is required for obtaining
  127. // the auth code and on refresh, this might be:
  128. //
  129. // viewController.authentication.additionalGrantTypeRequestParameters = @{
  130. // @"authorization_code" : @{ @"type" : @"code" },
  131. // @"refresh_token" : @{ @"type" : @"refresh" }
  132. // };
  133. @property (retain) NSDictionary *additionalGrantTypeRequestParameters;
  134. // Response properties
  135. @property (retain) NSMutableDictionary *parameters;
  136. @property (retain) NSString *accessToken;
  137. @property (retain) NSString *refreshToken;
  138. @property (retain) NSNumber *expiresIn;
  139. @property (retain) NSString *code;
  140. @property (retain) NSString *errorString;
  141. // URL for obtaining access tokens
  142. @property (copy) NSURL *tokenURL;
  143. // Calculated expiration date (expiresIn seconds added to the
  144. // time the access token was received.)
  145. @property (copy) NSDate *expirationDate;
  146. // Service identifier, like "Google"; not used for authentication
  147. //
  148. // The provider name is just for allowing stored authorization to be associated
  149. // with the authorizing service.
  150. @property (copy) NSString *serviceProvider;
  151. // User ID; not used for authentication
  152. @property (retain) NSString *userID;
  153. // User email and verified status; not used for authentication
  154. //
  155. // The verified string can be checked with -boolValue. If the result is false,
  156. // then the email address is listed with the account on the server, but the
  157. // address has not been confirmed as belonging to the owner of the account.
  158. @property (retain) NSString *userEmail;
  159. @property (retain) NSString *userEmailIsVerified;
  160. // Property indicating if this auth has a refresh or access token so is suitable
  161. // for authorizing a request. This does not guarantee that the token is valid.
  162. @property (readonly) BOOL canAuthorize;
  163. // Property indicating if this object will authorize plain http request
  164. // (as well as any non-https requests.) Default is NO, only requests with the
  165. // scheme https are authorized, since security may be compromised if tokens
  166. // are sent over the wire using an unencrypted protocol like http.
  167. @property (assign) BOOL shouldAuthorizeAllRequests;
  168. // userData is retained for the convenience of the caller
  169. @property (retain) id userData;
  170. // Stored property values are retained for the convenience of the caller
  171. @property (retain) NSDictionary *properties;
  172. // Property for the optional fetcher service instance to be used to create
  173. // fetchers
  174. //
  175. // Fetcher service objects retain authorizations, so this is weak to avoid
  176. // circular retains.
  177. @property (assign) id <GTMHTTPFetcherServiceProtocol> fetcherService; // WEAK
  178. // Alternative JSON parsing class; this should implement the
  179. // GTMOAuth2ParserClass informal protocol. If this property is
  180. // not set, the class SBJSON must be available in the runtime.
  181. @property (assign) Class parserClass;
  182. // Key for the response parameter used for the authorization header; by default,
  183. // "access_token" is used, but some servers may expect alternatives, like
  184. // "id_token".
  185. @property (copy) NSString *authorizationTokenKey;
  186. // Convenience method for creating an authentication object
  187. + (id)authenticationWithServiceProvider:(NSString *)serviceProvider
  188. tokenURL:(NSURL *)tokenURL
  189. redirectURI:(NSString *)redirectURI
  190. clientID:(NSString *)clientID
  191. clientSecret:(NSString *)clientSecret;
  192. // Clear out any authentication values, prepare for a new request fetch
  193. - (void)reset;
  194. // Main authorization entry points
  195. //
  196. // These will refresh the access token, if necessary, add the access token to
  197. // the request, then invoke the callback.
  198. //
  199. // The request argument may be nil to just force a refresh of the access token,
  200. // if needed.
  201. //
  202. // NOTE: To avoid accidental leaks of bearer tokens, the request must
  203. // be for a URL with the scheme https unless the shouldAuthorizeAllRequests
  204. // property is set.
  205. // The finish selector should have a signature matching
  206. // - (void)authentication:(GTMOAuth2Authentication *)auth
  207. // request:(NSMutableURLRequest *)request
  208. // finishedWithError:(NSError *)error;
  209. - (void)authorizeRequest:(NSMutableURLRequest *)request
  210. delegate:(id)delegate
  211. didFinishSelector:(SEL)sel;
  212. #if NS_BLOCKS_AVAILABLE
  213. - (void)authorizeRequest:(NSMutableURLRequest *)request
  214. completionHandler:(void (^)(NSError *error))handler;
  215. #endif
  216. // Synchronous entry point; authorizing this way cannot refresh an expired
  217. // access token
  218. - (BOOL)authorizeRequest:(NSMutableURLRequest *)request;
  219. // If the authentication is waiting for a refresh to complete, spin the run
  220. // loop, discarding events, until the fetch has completed
  221. //
  222. // This is only for use in testing or in tools without a user interface.
  223. - (void)waitForCompletionWithTimeout:(NSTimeInterval)timeoutInSeconds;
  224. //////////////////////////////////////////////////////////////////////////////
  225. //
  226. // Internal properties and methods for use by GTMOAuth2SignIn
  227. //
  228. // Pending fetcher to get a new access token, if any
  229. @property (retain) GTMHTTPFetcher *refreshFetcher;
  230. // Check if a request is queued up to be authorized
  231. - (BOOL)isAuthorizingRequest:(NSURLRequest *)request;
  232. // Check if a request appears to be authorized
  233. - (BOOL)isAuthorizedRequest:(NSURLRequest *)request;
  234. // Stop any pending refresh fetch. This will also cancel the authorization
  235. // for all fetch requests pending authorization.
  236. - (void)stopAuthorization;
  237. // Prevents authorization callback for a given request.
  238. - (void)stopAuthorizationForRequest:(NSURLRequest *)request;
  239. // OAuth fetch user-agent header value
  240. - (NSString *)userAgent;
  241. // Parse and set token and token secret from response data
  242. - (void)setKeysForResponseString:(NSString *)str;
  243. - (void)setKeysForResponseDictionary:(NSDictionary *)dict;
  244. // Persistent token string for keychain storage
  245. //
  246. // We'll use the format "refresh_token=foo&serviceProvider=bar" so we can
  247. // easily alter what portions of the auth data are stored
  248. //
  249. // Use these methods for serialization
  250. - (NSString *)persistenceResponseString;
  251. - (void)setKeysForPersistenceResponseString:(NSString *)str;
  252. // method to begin fetching an access token, used by the sign-in object
  253. - (GTMHTTPFetcher *)beginTokenFetchWithDelegate:(id)delegate
  254. didFinishSelector:(SEL)finishedSel;
  255. // Entry point to post a notification about a fetcher currently used for
  256. // obtaining or refreshing a token; the sign-in object will also use this
  257. // to indicate when the user's email address is being fetched.
  258. //
  259. // Fetch type constants are above under "notifications for token fetches"
  260. - (void)notifyFetchIsRunning:(BOOL)isStarting
  261. fetcher:(GTMHTTPFetcher *)fetcher
  262. type:(NSString *)fetchType;
  263. // Arbitrary key-value properties retained for the user
  264. - (void)setProperty:(id)obj forKey:(NSString *)key;
  265. - (id)propertyForKey:(NSString *)key;
  266. //
  267. // Utilities
  268. //
  269. + (NSString *)encodedOAuthValueForString:(NSString *)str;
  270. + (NSString *)encodedQueryParametersForDictionary:(NSDictionary *)dict;
  271. + (NSDictionary *)dictionaryWithResponseString:(NSString *)responseStr;
  272. + (NSDictionary *)dictionaryWithJSONData:(NSData *)data;
  273. + (NSString *)scopeWithStrings:(NSString *)firstStr, ... NS_REQUIRES_NIL_TERMINATION;
  274. @end
  275. #endif // GTM_INCLUDE_OAUTH2 || !GDATA_REQUIRE_SERVICE_INCLUDES