Commit f6ec60fc by AnilKumar PS

Pod installed

parent 0f8c7310
......@@ -16,6 +16,7 @@
049C2B4425DE4696002A0706 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 049C2B4225DE4696002A0706 /* LaunchScreen.storyboard */; };
049C2B4F25DE4696002A0706 /* CoreDataDemoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 049C2B4E25DE4696002A0706 /* CoreDataDemoTests.swift */; };
049C2B5A25DE4696002A0706 /* CoreDataDemoUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 049C2B5925DE4696002A0706 /* CoreDataDemoUITests.swift */; };
80F1DEC13616D571922E7867 /* Pods_CoreDataDemo.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 8D19779320F75C127A47B5B6 /* Pods_CoreDataDemo.framework */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
......@@ -51,6 +52,9 @@
049C2B5525DE4696002A0706 /* CoreDataDemoUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = CoreDataDemoUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
049C2B5925DE4696002A0706 /* CoreDataDemoUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CoreDataDemoUITests.swift; sourceTree = "<group>"; };
049C2B5B25DE4696002A0706 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
6A0D77D708C45FB48921BF02 /* Pods-CoreDataDemo.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-CoreDataDemo.debug.xcconfig"; path = "Target Support Files/Pods-CoreDataDemo/Pods-CoreDataDemo.debug.xcconfig"; sourceTree = "<group>"; };
8D19779320F75C127A47B5B6 /* Pods_CoreDataDemo.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_CoreDataDemo.framework; sourceTree = BUILT_PRODUCTS_DIR; };
FA73347AD5D24411DF29DD7F /* Pods-CoreDataDemo.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-CoreDataDemo.release.xcconfig"; path = "Target Support Files/Pods-CoreDataDemo/Pods-CoreDataDemo.release.xcconfig"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
......@@ -58,6 +62,7 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
80F1DEC13616D571922E7867 /* Pods_CoreDataDemo.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
......@@ -85,6 +90,8 @@
049C2B4D25DE4696002A0706 /* CoreDataDemoTests */,
049C2B5825DE4696002A0706 /* CoreDataDemoUITests */,
049C2B3225DE4693002A0706 /* Products */,
5D44A0EC10D6BDAD32DCD16B /* Pods */,
C5A6CF284C2A38A7C832FD2C /* Frameworks */,
);
sourceTree = "<group>";
};
......@@ -131,6 +138,24 @@
path = CoreDataDemoUITests;
sourceTree = "<group>";
};
5D44A0EC10D6BDAD32DCD16B /* Pods */ = {
isa = PBXGroup;
children = (
6A0D77D708C45FB48921BF02 /* Pods-CoreDataDemo.debug.xcconfig */,
FA73347AD5D24411DF29DD7F /* Pods-CoreDataDemo.release.xcconfig */,
);
name = Pods;
path = Pods;
sourceTree = "<group>";
};
C5A6CF284C2A38A7C832FD2C /* Frameworks */ = {
isa = PBXGroup;
children = (
8D19779320F75C127A47B5B6 /* Pods_CoreDataDemo.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
......@@ -138,9 +163,12 @@
isa = PBXNativeTarget;
buildConfigurationList = 049C2B5E25DE4696002A0706 /* Build configuration list for PBXNativeTarget "CoreDataDemo" */;
buildPhases = (
130BE9081620CD3BCC314115 /* [CP] Check Pods Manifest.lock */,
049C2B2D25DE4693002A0706 /* Sources */,
049C2B2E25DE4693002A0706 /* Frameworks */,
049C2B2F25DE4693002A0706 /* Resources */,
A8DA1E9FF4B4273AAA46F786 /* [CP] Embed Pods Frameworks */,
A0B90EE0C49D55275209CFB3 /* [CP] Copy Pods Resources */,
);
buildRules = (
);
......@@ -257,6 +285,65 @@
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
130BE9081620CD3BCC314115 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-CoreDataDemo-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
A0B90EE0C49D55275209CFB3 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-CoreDataDemo/Pods-CoreDataDemo-resources-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Copy Pods Resources";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-CoreDataDemo/Pods-CoreDataDemo-resources-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-CoreDataDemo/Pods-CoreDataDemo-resources.sh\"\n";
showEnvVarsInLog = 0;
};
A8DA1E9FF4B4273AAA46F786 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-CoreDataDemo/Pods-CoreDataDemo-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-CoreDataDemo/Pods-CoreDataDemo-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-CoreDataDemo/Pods-CoreDataDemo-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
049C2B2D25DE4693002A0706 /* Sources */ = {
isa = PBXSourcesBuildPhase;
......@@ -436,6 +523,7 @@
};
049C2B5F25DE4696002A0706 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 6A0D77D708C45FB48921BF02 /* Pods-CoreDataDemo.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
......@@ -454,6 +542,7 @@
};
049C2B6025DE4696002A0706 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = FA73347AD5D24411DF29DD7F /* Pods-CoreDataDemo.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CODE_SIGN_STYLE = Automatic;
......
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:CoreDataDemo.xcodeproj">
</FileRef>
<FileRef
location = "group:Pods/Pods.xcodeproj">
</FileRef>
</Workspace>
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'CoreDataDemo' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for CoreDataDemo
pod 'GoogleSignIn'
end
PODS:
- AppAuth (1.4.0):
- AppAuth/Core (= 1.4.0)
- AppAuth/ExternalUserAgent (= 1.4.0)
- AppAuth/Core (1.4.0)
- AppAuth/ExternalUserAgent (1.4.0)
- GoogleSignIn (5.0.2):
- AppAuth (~> 1.2)
- GTMAppAuth (~> 1.0)
- GTMSessionFetcher/Core (~> 1.1)
- GTMAppAuth (1.2.1):
- AppAuth/Core (~> 1.4)
- GTMSessionFetcher/Core (~> 1.5)
- GTMSessionFetcher/Core (1.5.0)
DEPENDENCIES:
- GoogleSignIn
SPEC REPOS:
trunk:
- AppAuth
- GoogleSignIn
- GTMAppAuth
- GTMSessionFetcher
SPEC CHECKSUMS:
AppAuth: 31bcec809a638d7bd2f86ea8a52bd45f6e81e7c7
GoogleSignIn: 7137d297ddc022a7e0aa4619c86d72c909fa7213
GTMAppAuth: 5b53231ef6920f149ab84b2969cb0ab572da3077
GTMSessionFetcher: b3503b20a988c4e20cc189aa798fd18220133f52
PODFILE CHECKSUM: 49b4ec5d3f10fda3f594af5d83ebc91a4414e838
COCOAPODS: 1.10.0.rc.1
/*! @file AppAuth.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDAuthState.h"
#import "OIDAuthStateChangeDelegate.h"
#import "OIDAuthStateErrorDelegate.h"
#import "OIDAuthorizationRequest.h"
#import "OIDAuthorizationResponse.h"
#import "OIDAuthorizationService.h"
#import "OIDError.h"
#import "OIDErrorUtilities.h"
#import "OIDExternalUserAgent.h"
#import "OIDExternalUserAgentRequest.h"
#import "OIDExternalUserAgentSession.h"
#import "OIDGrantTypes.h"
#import "OIDIDToken.h"
#import "OIDRegistrationRequest.h"
#import "OIDRegistrationResponse.h"
#import "OIDResponseTypes.h"
#import "OIDScopes.h"
#import "OIDScopeUtilities.h"
#import "OIDServiceConfiguration.h"
#import "OIDServiceDiscovery.h"
#import "OIDTokenRequest.h"
#import "OIDTokenResponse.h"
#import "OIDTokenUtilities.h"
#import "OIDURLSessionProvider.h"
#import "OIDEndSessionRequest.h"
#import "OIDEndSessionResponse.h"
#if TARGET_OS_TV
#elif TARGET_OS_WATCH
#elif TARGET_OS_IOS || TARGET_OS_MACCATALYST
#import "OIDAuthState+IOS.h"
#import "OIDAuthorizationService+IOS.h"
#import "OIDExternalUserAgentIOS.h"
#import "OIDExternalUserAgentIOSCustomBrowser.h"
#import "OIDExternalUserAgentCatalyst.h"
#elif TARGET_OS_MAC
#import "OIDAuthState+Mac.h"
#import "OIDAuthorizationService+Mac.h"
#import "OIDExternalUserAgentMac.h"
#import "OIDRedirectHTTPHandler.h"
#else
#error "Platform Undefined"
#endif
/*! @mainpage AppAuth for iOS and macOS
@section introduction Introduction
AppAuth for iOS and macOS is a client SDK for communicating with [OAuth 2.0]
(https://tools.ietf.org/html/rfc6749) and [OpenID Connect]
(http://openid.net/specs/openid-connect-core-1_0.html) providers. It strives to
directly map the requests and responses of those specifications, while following
the idiomatic style of the implementation language. In addition to mapping the
raw protocol flows, convenience methods are available to assist with common
tasks like performing an action with fresh tokens.
It follows the best practices set out in
[RFC 8252 - OAuth 2.0 for Native Apps](https://tools.ietf.org/html/rfc8252)
including using `SFAuthenticationSession` and `SFSafariViewController` on iOS
for the auth request. Web view and `WKWebView` are explicitly *not*
supported due to the security and usability reasons explained in
[Section 8.12 of RFC 8252](https://tools.ietf.org/html/rfc8252#section-8.12).
It also supports the [PKCE](https://tools.ietf.org/html/rfc7636) extension to
OAuth which was created to secure authorization codes in public clients when
custom URI scheme redirects are used. The library is friendly to other
extensions (standard or otherwise) with the ability to handle additional params
in all protocol requests and responses.
<b>Homepage</b>: http://openid.github.io/AppAuth-iOS/ <br>
<b>API Documentation</b>: http://openid.github.io/AppAuth-iOS/docs/latest <br>
<b>Git Repository</b>: https://github.com/openid/AppAuth-iOS <br>
*/
/*! @file OIDAuthState+IOS.h
@brief AppAuth iOS SDK
@copyright
Copyright 2016 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_MACCATALYST
#import <UIKit/UIKit.h>
#import "OIDAuthState.h"
NS_ASSUME_NONNULL_BEGIN
/*! @brief iOS specific convenience methods for @c OIDAuthState.
*/
@interface OIDAuthState (IOS)
/*! @brief Convenience method to create a @c OIDAuthState by presenting an authorization request
and performing the authorization code exchange in the case of code flow requests. For
the hybrid flow, the caller should validate the id_token and c_hash, then perform the token
request (@c OIDAuthorizationService.performTokenRequest:callback:)
and update the OIDAuthState with the results (@c
OIDAuthState.updateWithTokenResponse:error:).
@param authorizationRequest The authorization request to present.
@param presentingViewController The view controller from which to present the
@c SFSafariViewController. On iOS 13, the window of this UIViewController
is used as the ASPresentationAnchor.
@param callback The method called when the request has completed or failed.
@return A @c OIDExternalUserAgentSession instance which will terminate when it
receives a @c OIDExternalUserAgentSession.cancel message, or after processing a
@c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message.
*/
+ (id<OIDExternalUserAgentSession>)
authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest
presentingViewController:(UIViewController *)presentingViewController
callback:(OIDAuthStateAuthorizationCallback)callback;
+ (id<OIDExternalUserAgentSession>)
authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest
callback:(OIDAuthStateAuthorizationCallback)callback API_AVAILABLE(ios(11)) API_UNAVAILABLE(macCatalyst)
__deprecated_msg("This method will not work on iOS 13. Use "
"authStateByPresentingAuthorizationRequest:presentingViewController:callback:");
@end
NS_ASSUME_NONNULL_END
#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
/*! @file OIDAuthState+IOS.m
@brief AppAuth iOS SDK
@copyright
Copyright 2016 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_MACCATALYST
#import "OIDAuthState+IOS.h"
#import "OIDExternalUserAgentIOS.h"
#import "OIDExternalUserAgentCatalyst.h"
@implementation OIDAuthState (IOS)
+ (id<OIDExternalUserAgentSession>)
authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest
presentingViewController:(UIViewController *)presentingViewController
callback:(OIDAuthStateAuthorizationCallback)callback {
id<OIDExternalUserAgent> externalUserAgent;
#if TARGET_OS_MACCATALYST
externalUserAgent = [[OIDExternalUserAgentCatalyst alloc]
initWithPresentingViewController:presentingViewController];
#else // TARGET_OS_MACCATALYST
externalUserAgent = [[OIDExternalUserAgentIOS alloc] initWithPresentingViewController:presentingViewController];
#endif // TARGET_OS_MACCATALYST
return [self authStateByPresentingAuthorizationRequest:authorizationRequest
externalUserAgent:externalUserAgent
callback:callback];
}
#if !TARGET_OS_MACCATALYST
+ (id<OIDExternalUserAgentSession>)
authStateByPresentingAuthorizationRequest:(OIDAuthorizationRequest *)authorizationRequest
callback:(OIDAuthStateAuthorizationCallback)callback {
OIDExternalUserAgentIOS *externalUserAgent = [[OIDExternalUserAgentIOS alloc] init];
return [self authStateByPresentingAuthorizationRequest:authorizationRequest
externalUserAgent:externalUserAgent
callback:callback];
}
#endif // !TARGET_OS_MACCATALYST
@end
#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
/*! @file OIDAuthorizationService+IOS.h
@brief AppAuth iOS SDK
@copyright
Copyright 2016 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_MACCATALYST
#import <UIKit/UIKit.h>
#import "OIDAuthorizationService.h"
#import "OIDExternalUserAgentSession.h"
NS_ASSUME_NONNULL_BEGIN
/*! @brief Provides iOS specific authorization request handling.
*/
@interface OIDAuthorizationService (IOS)
/*! @brief Perform an authorization flow using \SFSafariViewController.
@param request The authorization request.
@param presentingViewController The view controller from which to present the
\SFSafariViewController.
@param callback The method called when the request has completed or failed.
@return A @c OIDExternalUserAgentSession instance which will terminate when it
receives a @c OIDExternalUserAgentSession.cancel message, or after processing a
@c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message.
*/
+ (id<OIDExternalUserAgentSession>) presentAuthorizationRequest:(OIDAuthorizationRequest *)request
presentingViewController:(UIViewController *)presentingViewController
callback:(OIDAuthorizationCallback)callback;
@end
NS_ASSUME_NONNULL_END
#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
/*! @file OIDAuthorizationService+IOS.m
@brief AppAuth iOS SDK
@copyright
Copyright 2016 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_MACCATALYST
#import "OIDAuthorizationService+IOS.h"
#import "OIDExternalUserAgentIOS.h"
#import "OIDExternalUserAgentCatalyst.h"
NS_ASSUME_NONNULL_BEGIN
@implementation OIDAuthorizationService (IOS)
+ (id<OIDExternalUserAgentSession>) presentAuthorizationRequest:(OIDAuthorizationRequest *)request
presentingViewController:(UIViewController *)presentingViewController
callback:(OIDAuthorizationCallback)callback {
id<OIDExternalUserAgent> externalUserAgent;
#if TARGET_OS_MACCATALYST
externalUserAgent = [[OIDExternalUserAgentCatalyst alloc]
initWithPresentingViewController:presentingViewController];
#else // TARGET_OS_MACCATALYST
externalUserAgent = [[OIDExternalUserAgentIOS alloc] initWithPresentingViewController:presentingViewController];
#endif // TARGET_OS_MACCATALYST
return [self presentAuthorizationRequest:request externalUserAgent:externalUserAgent callback:callback];
}
@end
NS_ASSUME_NONNULL_END
#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
/*! @file OIDExternalUserAgentCatalyst.h
@brief AppAuth iOS SDK
@copyright
Copyright 2019 The AppAuth Authors. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_MACCATALYST
#import <UIKit/UIKit.h>
#import "OIDExternalUserAgent.h"
NS_ASSUME_NONNULL_BEGIN
/*! @brief A Catalyst specific external user-agent that uses `ASWebAuthenticationSession` to
present the request.
*/
API_AVAILABLE(macCatalyst(13)) API_UNAVAILABLE(ios)
@interface OIDExternalUserAgentCatalyst : NSObject<OIDExternalUserAgent>
/*! @internal
@brief Unavailable. Please use @c initWithPresentingViewController:
*/
- (nonnull instancetype)init NS_UNAVAILABLE;
/*! @brief The designated initializer.
@param presentingViewController The view controller from which to present the
\SFSafariViewController.
*/
- (nullable instancetype)initWithPresentingViewController:
(UIViewController *)presentingViewController
NS_DESIGNATED_INITIALIZER;
@end
NS_ASSUME_NONNULL_END
#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
/*! @file OIDExternalUserAgentCatalyst.m
@brief AppAuth iOS SDK
@copyright
Copyright 2019 The AppAuth Authors. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_MACCATALYST
#import "OIDExternalUserAgentCatalyst.h"
#import <SafariServices/SafariServices.h>
#import <AuthenticationServices/AuthenticationServices.h>
#import "OIDErrorUtilities.h"
#import "OIDExternalUserAgentSession.h"
#import "OIDExternalUserAgentRequest.h"
#if TARGET_OS_MACCATALYST
NS_ASSUME_NONNULL_BEGIN
@interface OIDExternalUserAgentCatalyst ()<ASWebAuthenticationPresentationContextProviding>
@end
@implementation OIDExternalUserAgentCatalyst {
UIViewController *_presentingViewController;
BOOL _externalUserAgentFlowInProgress;
__weak id<OIDExternalUserAgentSession> _session;
ASWebAuthenticationSession *_webAuthenticationVC;
}
- (nullable instancetype)initWithPresentingViewController:
(UIViewController *)presentingViewController {
self = [super init];
if (self) {
_presentingViewController = presentingViewController;
}
return self;
}
- (BOOL)presentExternalUserAgentRequest:(id<OIDExternalUserAgentRequest>)request
session:(id<OIDExternalUserAgentSession>)session {
if (_externalUserAgentFlowInProgress) {
// TODO: Handle errors as authorization is already in progress.
return NO;
}
_externalUserAgentFlowInProgress = YES;
_session = session;
BOOL openedUserAgent = NO;
NSURL *requestURL = [request externalUserAgentRequestURL];
__weak OIDExternalUserAgentCatalyst *weakSelf = self;
NSString *redirectScheme = request.redirectScheme;
ASWebAuthenticationSession *authenticationVC =
[[ASWebAuthenticationSession alloc] initWithURL:requestURL
callbackURLScheme:redirectScheme
completionHandler:^(NSURL * _Nullable callbackURL,
NSError * _Nullable error) {
__strong OIDExternalUserAgentCatalyst *strongSelf = weakSelf;
if (!strongSelf) {
return;
}
strongSelf->_webAuthenticationVC = nil;
if (callbackURL) {
[strongSelf->_session resumeExternalUserAgentFlowWithURL:callbackURL];
} else {
NSError *safariError =
[OIDErrorUtilities errorWithCode:OIDErrorCodeUserCanceledAuthorizationFlow
underlyingError:error
description:nil];
[strongSelf->_session failExternalUserAgentFlowWithError:safariError];
}
}];
authenticationVC.presentationContextProvider = self;
_webAuthenticationVC = authenticationVC;
openedUserAgent = [authenticationVC start];
if (!openedUserAgent) {
[self cleanUp];
NSError *safariError = [OIDErrorUtilities errorWithCode:OIDErrorCodeSafariOpenError
underlyingError:nil
description:@"Unable to open ASWebAuthenticationSession view controller."];
[session failExternalUserAgentFlowWithError:safariError];
}
return openedUserAgent;
}
- (void)dismissExternalUserAgentAnimated:(BOOL)animated completion:(void (^)(void))completion {
if (!_externalUserAgentFlowInProgress) {
// Ignore this call if there is no authorization flow in progress.
if (completion) completion();
return;
}
ASWebAuthenticationSession *webAuthenticationVC = _webAuthenticationVC;
[self cleanUp];
if (webAuthenticationVC) {
// dismiss the ASWebAuthenticationSession
[webAuthenticationVC cancel];
if (completion) completion();
} else {
if (completion) completion();
}
}
- (void)cleanUp {
// The weak reference to |_session| is set to nil to avoid accidentally using
// it while not in an authorization flow.
_webAuthenticationVC = nil;
_session = nil;
_externalUserAgentFlowInProgress = NO;
}
#pragma mark - ASWebAuthenticationPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuthenticationSession *)session {
return _presentingViewController.view.window;
}
@end
NS_ASSUME_NONNULL_END
#endif // TARGET_OS_MACCATALYST
#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
/*! @file OIDExternalUserAgentIOS.h
@brief AppAuth iOS SDK
@copyright
Copyright 2016 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_MACCATALYST
#import <UIKit/UIKit.h>
#import "OIDExternalUserAgent.h"
@class SFSafariViewController;
NS_ASSUME_NONNULL_BEGIN
/*! @brief An iOS specific external user-agent that uses the best possible user-agent available
depending on the version of iOS to present the request.
*/
API_UNAVAILABLE(macCatalyst)
@interface OIDExternalUserAgentIOS : NSObject<OIDExternalUserAgent>
- (nullable instancetype)init API_AVAILABLE(ios(11))
__deprecated_msg("This method will not work on iOS 13, use "
"initWithPresentingViewController:presentingViewController");
/*! @brief The designated initializer.
@param presentingViewController The view controller from which to present the
\SFSafariViewController.
*/
- (nullable instancetype)initWithPresentingViewController:
(UIViewController *)presentingViewController
NS_DESIGNATED_INITIALIZER;
@end
NS_ASSUME_NONNULL_END
#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
/*! @file OIDExternalUserAgentIOS.m
@brief AppAuth iOS SDK
@copyright
Copyright 2016 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_MACCATALYST
#import "OIDExternalUserAgentIOS.h"
#import <SafariServices/SafariServices.h>
#import <AuthenticationServices/AuthenticationServices.h>
#import "OIDErrorUtilities.h"
#import "OIDExternalUserAgentSession.h"
#import "OIDExternalUserAgentRequest.h"
#if !TARGET_OS_MACCATALYST
NS_ASSUME_NONNULL_BEGIN
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
@interface OIDExternalUserAgentIOS ()<SFSafariViewControllerDelegate, ASWebAuthenticationPresentationContextProviding>
@end
#else
@interface OIDExternalUserAgentIOS ()<SFSafariViewControllerDelegate>
@end
#endif
@implementation OIDExternalUserAgentIOS {
UIViewController *_presentingViewController;
BOOL _externalUserAgentFlowInProgress;
__weak id<OIDExternalUserAgentSession> _session;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
__weak SFSafariViewController *_safariVC;
SFAuthenticationSession *_authenticationVC;
ASWebAuthenticationSession *_webAuthenticationVC;
#pragma clang diagnostic pop
}
- (nullable instancetype)init {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wnonnull"
return [self initWithPresentingViewController:nil];
#pragma clang diagnostic pop
}
- (nullable instancetype)initWithPresentingViewController:
(UIViewController *)presentingViewController {
self = [super init];
if (self) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
NSAssert(presentingViewController != nil,
@"presentingViewController cannot be nil on iOS 13");
#endif // __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
_presentingViewController = presentingViewController;
}
return self;
}
- (BOOL)presentExternalUserAgentRequest:(id<OIDExternalUserAgentRequest>)request
session:(id<OIDExternalUserAgentSession>)session {
if (_externalUserAgentFlowInProgress) {
// TODO: Handle errors as authorization is already in progress.
return NO;
}
_externalUserAgentFlowInProgress = YES;
_session = session;
BOOL openedUserAgent = NO;
NSURL *requestURL = [request externalUserAgentRequestURL];
// iOS 12 and later, use ASWebAuthenticationSession
if (@available(iOS 12.0, *)) {
// ASWebAuthenticationSession doesn't work with guided access (rdar://40809553)
if (!UIAccessibilityIsGuidedAccessEnabled()) {
__weak OIDExternalUserAgentIOS *weakSelf = self;
NSString *redirectScheme = request.redirectScheme;
ASWebAuthenticationSession *authenticationVC =
[[ASWebAuthenticationSession alloc] initWithURL:requestURL
callbackURLScheme:redirectScheme
completionHandler:^(NSURL * _Nullable callbackURL,
NSError * _Nullable error) {
__strong OIDExternalUserAgentIOS *strongSelf = weakSelf;
if (!strongSelf) {
return;
}
strongSelf->_webAuthenticationVC = nil;
if (callbackURL) {
[strongSelf->_session resumeExternalUserAgentFlowWithURL:callbackURL];
} else {
NSError *safariError =
[OIDErrorUtilities errorWithCode:OIDErrorCodeUserCanceledAuthorizationFlow
underlyingError:error
description:nil];
[strongSelf->_session failExternalUserAgentFlowWithError:safariError];
}
}];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
if (@available(iOS 13.0, *)) {
authenticationVC.presentationContextProvider = self;
}
#endif
_webAuthenticationVC = authenticationVC;
openedUserAgent = [authenticationVC start];
}
}
// iOS 11, use SFAuthenticationSession
if (@available(iOS 11.0, *)) {
// SFAuthenticationSession doesn't work with guided access (rdar://40809553)
if (!openedUserAgent && !UIAccessibilityIsGuidedAccessEnabled()) {
__weak OIDExternalUserAgentIOS *weakSelf = self;
NSString *redirectScheme = request.redirectScheme;
SFAuthenticationSession *authenticationVC =
[[SFAuthenticationSession alloc] initWithURL:requestURL
callbackURLScheme:redirectScheme
completionHandler:^(NSURL * _Nullable callbackURL,
NSError * _Nullable error) {
__strong OIDExternalUserAgentIOS *strongSelf = weakSelf;
if (!strongSelf) {
return;
}
strongSelf->_authenticationVC = nil;
if (callbackURL) {
[strongSelf->_session resumeExternalUserAgentFlowWithURL:callbackURL];
} else {
NSError *safariError =
[OIDErrorUtilities errorWithCode:OIDErrorCodeUserCanceledAuthorizationFlow
underlyingError:error
description:@"User cancelled."];
[strongSelf->_session failExternalUserAgentFlowWithError:safariError];
}
}];
_authenticationVC = authenticationVC;
openedUserAgent = [authenticationVC start];
}
}
// iOS 9 and 10, use SFSafariViewController
if (@available(iOS 9.0, *)) {
if (!openedUserAgent && _presentingViewController) {
SFSafariViewController *safariVC =
[[SFSafariViewController alloc] initWithURL:requestURL];
safariVC.delegate = self;
_safariVC = safariVC;
[_presentingViewController presentViewController:safariVC animated:YES completion:nil];
openedUserAgent = YES;
}
}
// iOS 8 and earlier, use mobile Safari
if (!openedUserAgent){
openedUserAgent = [[UIApplication sharedApplication] openURL:requestURL];
}
if (!openedUserAgent) {
[self cleanUp];
NSError *safariError = [OIDErrorUtilities errorWithCode:OIDErrorCodeSafariOpenError
underlyingError:nil
description:@"Unable to open Safari."];
[session failExternalUserAgentFlowWithError:safariError];
}
return openedUserAgent;
}
- (void)dismissExternalUserAgentAnimated:(BOOL)animated completion:(void (^)(void))completion {
if (!_externalUserAgentFlowInProgress) {
// Ignore this call if there is no authorization flow in progress.
if (completion) completion();
return;
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wpartial-availability"
SFSafariViewController *safariVC = _safariVC;
SFAuthenticationSession *authenticationVC = _authenticationVC;
ASWebAuthenticationSession *webAuthenticationVC = _webAuthenticationVC;
#pragma clang diagnostic pop
[self cleanUp];
if (webAuthenticationVC) {
// dismiss the ASWebAuthenticationSession
[webAuthenticationVC cancel];
if (completion) completion();
} else if (authenticationVC) {
// dismiss the SFAuthenticationSession
[authenticationVC cancel];
if (completion) completion();
} else if (safariVC) {
// dismiss the SFSafariViewController
[safariVC dismissViewControllerAnimated:YES completion:completion];
} else {
if (completion) completion();
}
}
- (void)cleanUp {
// The weak references to |_safariVC| and |_session| are set to nil to avoid accidentally using
// them while not in an authorization flow.
_safariVC = nil;
_authenticationVC = nil;
_webAuthenticationVC = nil;
_session = nil;
_externalUserAgentFlowInProgress = NO;
}
#pragma mark - SFSafariViewControllerDelegate
- (void)safariViewControllerDidFinish:(SFSafariViewController *)controller NS_AVAILABLE_IOS(9.0) {
if (controller != _safariVC) {
// Ignore this call if the safari view controller do not match.
return;
}
if (!_externalUserAgentFlowInProgress) {
// Ignore this call if there is no authorization flow in progress.
return;
}
id<OIDExternalUserAgentSession> session = _session;
[self cleanUp];
NSError *error = [OIDErrorUtilities errorWithCode:OIDErrorCodeUserCanceledAuthorizationFlow
underlyingError:nil
description:@"No external user agent flow in progress."];
[session failExternalUserAgentFlowWithError:error];
}
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
#pragma mark - ASWebAuthenticationPresentationContextProviding
- (ASPresentationAnchor)presentationAnchorForWebAuthenticationSession:(ASWebAuthenticationSession *)session API_AVAILABLE(ios(13.0)){
return _presentingViewController.view.window;
}
#endif // __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
@end
NS_ASSUME_NONNULL_END
#endif // !TARGET_OS_MACCATALYST
#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
/*! @file OIDExternalUserAgentIOSCustomBrowser.h
@brief AppAuth iOS SDK
@copyright
Copyright 2018 Google LLC
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_MACCATALYST
#import <Foundation/Foundation.h>
#import "OIDExternalUserAgent.h"
NS_ASSUME_NONNULL_BEGIN
/*! @brief A block that transforms a regular http/https URL into one that will open in an
alternative browser.
@param requestURL the http/https request URL to be transformed.
@return transformed URL.
*/
typedef NSURL *_Nullable (^OIDCustomBrowserURLTransformation)(NSURL *_Nullable requestURL);
/*! @brief An implementation of the OIDExternalUserAgent protocol for iOS that uses
a custom browser (i.e. not Safari) for external requests. It is suitable for browsers that
offer a custom url scheme that simply replaces the "https" scheme. It is not designed
for browsers that require other modifications to the URL. If the browser is not installed
the user will be prompted to install it.
*/
API_UNAVAILABLE(macCatalyst)
@interface OIDExternalUserAgentIOSCustomBrowser : NSObject<OIDExternalUserAgent>
/*! @brief URL transformation block for the browser.
*/
@property(nonatomic, readonly) OIDCustomBrowserURLTransformation URLTransformation;
/*! @brief URL Scheme used to test for whether the browser is installed.
*/
@property(nonatomic, readonly, nullable) NSString *canOpenURLScheme;
/*! @brief URL of the browser's App Store listing.
*/
@property(nonatomic, readonly, nullable) NSURL *appStoreURL;
/*! @brief An instance of @c OIDExternalUserAgentIOSCustomBrowser for Chrome.
*/
+ (instancetype)CustomBrowserChrome;
/*! @brief An instance of @c OIDExternalUserAgentIOSCustomBrowser for Firefox.
*/
+ (instancetype)CustomBrowserFirefox;
/*! @brief An instance of @c OIDExternalUserAgentIOSCustomBrowser for Opera.
*/
+ (instancetype)CustomBrowserOpera;
/*! @brief An instance of @c OIDExternalUserAgentIOSCustomBrowser for Safari.
*/
+ (instancetype)CustomBrowserSafari;
/*! @brief Creates a @c OIDCustomBrowserURLTransformation using the scheme substitution method used
iOS browsers like Chrome and Firefox.
*/
+ (OIDCustomBrowserURLTransformation)
URLTransformationSchemeSubstitutionHTTPS:(NSString *)browserSchemeHTTPS
HTTP:(nullable NSString *)browserSchemeHTTP;
/*! @brief Creates a @c OIDCustomBrowserURLTransformation with the URL prefix method used by
iOS browsers like Firefox.
*/
+ (OIDCustomBrowserURLTransformation) URLTransformationSchemeConcatPrefix:(NSString*)URLprefix;
/*! @internal
@brief Unavailable. Please use @c initWithURLTransformation:canOpenURLScheme:appStoreURL:
*/
- (nonnull instancetype)init NS_UNAVAILABLE;
/*! @brief OIDExternalUserAgent for a custom browser. @c presentExternalUserAgentRequest:session method
will return NO if the browser isn't installed.
*/
- (nullable instancetype)initWithURLTransformation:(OIDCustomBrowserURLTransformation)URLTransformation;
/*! @brief The designated initializer.
@param URLTransformation the transformation block to translate the URL into one that will open
in the desired custom browser.
@param canOpenURLScheme any scheme supported by the browser used to check if the browser is
installed.
@param appStoreURL URL of the browser in the app store. When this and @c canOpenURLScheme
are non-nil, @c presentExternalUserAgentRequest:session will redirect the user to the app store
if the browser is not installed.
*/
- (nullable instancetype)initWithURLTransformation:(OIDCustomBrowserURLTransformation)URLTransformation
canOpenURLScheme:(nullable NSString *)canOpenURLScheme
appStoreURL:(nullable NSURL *)appStoreURL
NS_DESIGNATED_INITIALIZER;
@end
NS_ASSUME_NONNULL_END
#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
/*! @file OIDExternalUserAgentIOSCustomBrowser.m
@brief AppAuth iOS SDK
@copyright
Copyright 2018 Google LLC
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <TargetConditionals.h>
#if TARGET_OS_IOS || TARGET_OS_MACCATALYST
#import "OIDExternalUserAgentIOSCustomBrowser.h"
#import <UIKit/UIKit.h>
#import "OIDAuthorizationRequest.h"
#import "OIDAuthorizationService.h"
#import "OIDErrorUtilities.h"
#import "OIDURLQueryComponent.h"
#if !TARGET_OS_MACCATALYST
NS_ASSUME_NONNULL_BEGIN
@implementation OIDExternalUserAgentIOSCustomBrowser
+ (instancetype)CustomBrowserChrome {
// Chrome iOS documentation: https://developer.chrome.com/multidevice/ios/links
OIDCustomBrowserURLTransformation transform = [[self class] URLTransformationSchemeSubstitutionHTTPS:@"googlechromes" HTTP:@"googlechrome"];
NSURL *appStoreURL =
[NSURL URLWithString:@"itms-apps://itunes.apple.com/us/app/chrome/id535886823"];
return [[[self class] alloc] initWithURLTransformation:transform
canOpenURLScheme:@"googlechromes"
appStoreURL:appStoreURL];
}
+ (instancetype)CustomBrowserFirefox {
// Firefox iOS documentation: https://github.com/mozilla-mobile/firefox-ios-open-in-client
OIDCustomBrowserURLTransformation transform =
[[self class] URLTransformationSchemeConcatPrefix:@"firefox://open-url?url="];
NSURL *appStoreURL =
[NSURL URLWithString:@"itms-apps://itunes.apple.com/us/app/firefox-web-browser/id989804926"];
return [[[self class] alloc] initWithURLTransformation:transform
canOpenURLScheme:@"firefox"
appStoreURL:appStoreURL];
}
+ (instancetype)CustomBrowserOpera {
OIDCustomBrowserURLTransformation transform =
[[self class] URLTransformationSchemeSubstitutionHTTPS:@"opera-https" HTTP:@"opera-http"];
NSURL *appStoreURL =
[NSURL URLWithString:@"itms-apps://itunes.apple.com/us/app/opera-mini-web-browser/id363729560"];
return [[[self class] alloc] initWithURLTransformation:transform
canOpenURLScheme:@"opera-https"
appStoreURL:appStoreURL];
}
+ (instancetype)CustomBrowserSafari {
OIDCustomBrowserURLTransformation transformNOP = ^NSURL *(NSURL *requestURL) {
return requestURL;
};
OIDExternalUserAgentIOSCustomBrowser *transform =
[[[self class] alloc] initWithURLTransformation:transformNOP];
return transform;
}
+ (OIDCustomBrowserURLTransformation)
URLTransformationSchemeSubstitutionHTTPS:(NSString *)browserSchemeHTTPS
HTTP:(nullable NSString *)browserSchemeHTTP {
OIDCustomBrowserURLTransformation transform = ^NSURL *(NSURL *requestURL) {
// Replace the URL Scheme with the Chrome equivalent.
NSString *newScheme = nil;
if ([requestURL.scheme isEqualToString:@"https"]) {
newScheme = browserSchemeHTTPS;
} else if ([requestURL.scheme isEqualToString:@"http"]) {
if (!browserSchemeHTTP) {
NSAssert(false, @"No HTTP scheme registered for browser");
return nil;
}
newScheme = browserSchemeHTTP;
}
// Replaces the URI scheme with the custom scheme
NSURLComponents *components = [NSURLComponents componentsWithURL:requestURL
resolvingAgainstBaseURL:YES];
components.scheme = newScheme;
return components.URL;
};
return transform;
}
+ (OIDCustomBrowserURLTransformation)URLTransformationSchemeConcatPrefix:(NSString *)URLprefix {
OIDCustomBrowserURLTransformation transform = ^NSURL *(NSURL *requestURL) {
NSString *requestURLString = [requestURL absoluteString];
NSMutableCharacterSet *allowedParamCharacters =
[OIDURLQueryComponent URLParamValueAllowedCharacters];
NSString *encodedUrl = [requestURLString stringByAddingPercentEncodingWithAllowedCharacters:allowedParamCharacters];
NSString *newURL = [NSString stringWithFormat:@"%@%@", URLprefix, encodedUrl];
return [NSURL URLWithString:newURL];
};
return transform;
}
- (nullable instancetype)initWithURLTransformation:
(OIDCustomBrowserURLTransformation)URLTransformation {
return [self initWithURLTransformation:URLTransformation canOpenURLScheme:nil appStoreURL:nil];
}
- (nullable instancetype)
initWithURLTransformation:(OIDCustomBrowserURLTransformation)URLTransformation
canOpenURLScheme:(nullable NSString *)canOpenURLScheme
appStoreURL:(nullable NSURL *)appStoreURL {
self = [super init];
if (self) {
_URLTransformation = URLTransformation;
_canOpenURLScheme = canOpenURLScheme;
_appStoreURL = appStoreURL;
}
return self;
}
- (BOOL)presentExternalUserAgentRequest:(nonnull id<OIDExternalUserAgentRequest>)request
session:(nonnull id<OIDExternalUserAgentSession>)session {
// If the app store URL is set, checks if the app is installed and if not opens the app store.
if (_appStoreURL && _canOpenURLScheme) {
// Verifies existence of LSApplicationQueriesSchemes Info.plist key.
NSArray __unused* canOpenURLs =
[[NSBundle mainBundle] objectForInfoDictionaryKey:@"LSApplicationQueriesSchemes"];
NSAssert(canOpenURLs, @"plist missing LSApplicationQueriesSchemes key");
NSAssert1([canOpenURLs containsObject:_canOpenURLScheme],
@"plist missing LSApplicationQueriesSchemes entry for '%@'", _canOpenURLScheme);
// Opens AppStore if app isn't installed
NSString *testURLString = [NSString stringWithFormat:@"%@://example.com", _canOpenURLScheme];
NSURL *testURL = [NSURL URLWithString:testURLString];
if (![[UIApplication sharedApplication] canOpenURL:testURL]) {
[[UIApplication sharedApplication] openURL:_appStoreURL];
return NO;
}
}
// Transforms the request URL and opens it.
NSURL *requestURL = [request externalUserAgentRequestURL];
requestURL = _URLTransformation(requestURL);
BOOL openedInBrowser = [[UIApplication sharedApplication] openURL:requestURL];
return openedInBrowser;
}
- (void)dismissExternalUserAgentAnimated:(BOOL)animated
completion:(nonnull void (^)(void))completion {
completion();
}
@end
NS_ASSUME_NONNULL_END
#endif // !TARGET_OS_MACCATALYST
#endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
/*! @file AppAuthCore.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDAuthState.h"
#import "OIDAuthStateChangeDelegate.h"
#import "OIDAuthStateErrorDelegate.h"
#import "OIDAuthorizationRequest.h"
#import "OIDAuthorizationResponse.h"
#import "OIDAuthorizationService.h"
#import "OIDError.h"
#import "OIDErrorUtilities.h"
#import "OIDExternalUserAgent.h"
#import "OIDExternalUserAgentRequest.h"
#import "OIDExternalUserAgentSession.h"
#import "OIDGrantTypes.h"
#import "OIDIDToken.h"
#import "OIDRegistrationRequest.h"
#import "OIDRegistrationResponse.h"
#import "OIDResponseTypes.h"
#import "OIDScopes.h"
#import "OIDScopeUtilities.h"
#import "OIDServiceConfiguration.h"
#import "OIDServiceDiscovery.h"
#import "OIDTokenRequest.h"
#import "OIDTokenResponse.h"
#import "OIDTokenUtilities.h"
#import "OIDURLSessionProvider.h"
#import "OIDEndSessionRequest.h"
#import "OIDEndSessionResponse.h"
/*! @file OIDAuthStateChangeDelegate.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
@class OIDAuthState;
NS_ASSUME_NONNULL_BEGIN
/*! @protocol OIDAuthStateChangeDelegate
@brief Delegate of the OIDAuthState used to monitor various changes in state.
*/
@protocol OIDAuthStateChangeDelegate <NSObject>
/*! @brief Called when the authorization state changes and any backing storage needs to be updated.
@param state The @c OIDAuthState that changed.
@discussion If you are storing the authorization state, you should update the storage when the
state changes.
*/
- (void)didChangeState:(OIDAuthState *)state;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDAuthStateErrorDelegate.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
@class OIDAuthState;
NS_ASSUME_NONNULL_BEGIN
/*! @protocol OIDAuthStateErrorDelegate
@brief Delegate of the OIDAuthState used to monitor errors.
*/
@protocol OIDAuthStateErrorDelegate <NSObject>
/*! @brief Called when an authentication occurs, which indicates the auth session is invalid.
@param state The @c OIDAuthState on which the error occurred.
@param error The authorization error.
@discussion This is a hard error (not a transient network issue) that indicates a problem with
the authorization. You should stop using the @c OIDAuthState when such an error is
encountered. If the \NSError_code is @c ::OIDErrorCodeOAuthInvalidGrant then
the session may be recoverable with user interaction (i.e. re-authentication). In all cases
you should consider the user unauthorized, and remove locally cached resources that require
that authorization. @c OIDAuthState will call this method automatically if it encounters
an OAuth error (that is, an HTTP 400 response with a valid OAuth error response) during
authorization or token refresh (such as performed automatically when using
@c OIDAuthState.performActionWithFreshTokens:). You can signal authorization errors with
@c OIDAuthState.updateWithAuthorizationError:.
@see https://tools.ietf.org/html/rfc6749#section-5.2
*/
- (void)authState:(OIDAuthState *)state didEncounterAuthorizationError:(NSError *)error;
@optional
/*! @brief Called when a network or other transient error occurs.
@param state The @c OIDAuthState on which the error occurred.
@param error The transient error.
@discussion This is a soft error, typically network related. The @c OIDAuthState is likely
still valid, and should not be discarded. Retry the request using an incremental backoff
strategy. This is only called when using the @c OIDAuthState convenience methods such as
@c OIDAuthState.performActionWithFreshTokens:. If you are refreshing the tokens yourself
outside of @c OIDAuthState class, it will never be called.
*/
- (void)authState:(OIDAuthState *)state didEncounterTransientError:(NSError *)error;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDAuthorizationResponse.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
@class OIDAuthorizationRequest;
@class OIDTokenRequest;
NS_ASSUME_NONNULL_BEGIN
/*! @brief Represents the response to an authorization request.
@see https://tools.ietf.org/html/rfc6749#section-4.1.2
@see https://tools.ietf.org/html/rfc6749#section-5.1
@see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse
*/
@interface OIDAuthorizationResponse : NSObject <NSCopying, NSSecureCoding>
/*! @brief The request which was serviced.
*/
@property(nonatomic, readonly) OIDAuthorizationRequest *request;
/*! @brief The authorization code generated by the authorization server.
@discussion Set when the response_type requested includes 'code'.
@remarks code
*/
@property(nonatomic, readonly, nullable) NSString *authorizationCode;
/*! @brief REQUIRED if the "state" parameter was present in the client authorization request. The
exact value received from the client.
@remarks state
*/
@property(nonatomic, readonly, nullable) NSString *state;
/*! @brief The access token generated by the authorization server.
@discussion Set when the response_type requested includes 'token'.
@remarks access_token
@see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse
*/
@property(nonatomic, readonly, nullable) NSString *accessToken;
/*! @brief The approximate expiration date & time of the access token.
@discussion Set when the response_type requested includes 'token'.
@remarks expires_in
@seealso OIDAuthorizationResponse.accessToken
@see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse
*/
@property(nonatomic, readonly, nullable) NSDate *accessTokenExpirationDate;
/*! @brief Typically "Bearer" when present. Otherwise, another token_type value that the Client has
negotiated with the Authorization Server.
@discussion Set when the response_type requested includes 'token'.
@remarks token_type
@see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse
*/
@property(nonatomic, readonly, nullable) NSString *tokenType;
/*! @brief ID Token value associated with the authenticated session.
@discussion Set when the response_type requested includes 'id_token'.
@remarks id_token
@see http://openid.net/specs/openid-connect-core-1_0.html#IDToken
@see http://openid.net/specs/openid-connect-core-1_0.html#ImplicitAuthResponse
*/
@property(nonatomic, readonly, nullable) NSString *idToken;
/*! @brief The scope of the access token. OPTIONAL, if identical to the scopes requested, otherwise,
REQUIRED.
@remarks scope
@see https://tools.ietf.org/html/rfc6749#section-5.1
*/
@property(nonatomic, readonly, nullable) NSString *scope;
/*! @brief Additional parameters returned from the authorization server.
*/
@property(nonatomic, readonly, nullable)
NSDictionary<NSString *, NSObject<NSCopying> *> *additionalParameters;
/*! @internal
@brief Unavailable. Please use initWithRequest:parameters:.
*/
- (instancetype)init NS_UNAVAILABLE;
/*! @brief Designated initializer.
@param request The serviced request.
@param parameters The decoded parameters returned from the Authorization Server.
@remarks Known parameters are extracted from the @c parameters parameter and the normative
properties are populated. Non-normative parameters are placed in the
@c #additionalParameters dictionary.
*/
- (instancetype)initWithRequest:(OIDAuthorizationRequest *)request
parameters:(NSDictionary<NSString *, NSObject<NSCopying> *> *)parameters
NS_DESIGNATED_INITIALIZER;
/*! @brief Creates a token request suitable for exchanging an authorization code for an access
token.
@return A @c OIDTokenRequest suitable for exchanging an authorization code for an access
token.
@see https://tools.ietf.org/html/rfc6749#section-4.1.3
*/
- (nullable OIDTokenRequest *)tokenExchangeRequest;
/*! @brief Creates a token request suitable for exchanging an authorization code for an access
token.
@param additionalParameters Additional parameters for the token request.
@return A @c OIDTokenRequest suitable for exchanging an authorization code for an access
token.
@see https://tools.ietf.org/html/rfc6749#section-4.1.3
*/
- (nullable OIDTokenRequest *)tokenExchangeRequestWithAdditionalParameters:
(nullable NSDictionary<NSString *, NSString *> *)additionalParameters;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDAuthorizationResponse.m
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDAuthorizationResponse.h"
#import "OIDAuthorizationRequest.h"
#import "OIDDefines.h"
#import "OIDError.h"
#import "OIDFieldMapping.h"
#import "OIDTokenRequest.h"
#import "OIDTokenUtilities.h"
/*! @brief The key for the @c authorizationCode property in the incoming parameters and for
@c NSSecureCoding.
*/
static NSString *const kAuthorizationCodeKey = @"code";
/*! @brief The key for the @c state property in the incoming parameters and for @c NSSecureCoding.
*/
static NSString *const kStateKey = @"state";
/*! @brief The key for the @c accessToken property in the incoming parameters and for
@c NSSecureCoding.
*/
static NSString *const kAccessTokenKey = @"access_token";
/*! @brief The key for the @c accessTokenExpirationDate property in the incoming parameters and for
@c NSSecureCoding.
*/
static NSString *const kExpiresInKey = @"expires_in";
/*! @brief The key for the @c tokenType property in the incoming parameters and for
@c NSSecureCoding.
*/
static NSString *const kTokenTypeKey = @"token_type";
/*! @brief The key for the @c idToken property in the incoming parameters and for @c NSSecureCoding.
*/
static NSString *const kIDTokenKey = @"id_token";
/*! @brief The key for the @c scope property in the incoming parameters and for @c NSSecureCoding.
*/
static NSString *const kScopeKey = @"scope";
/*! @brief Key used to encode the @c additionalParameters property for @c NSSecureCoding
*/
static NSString *const kAdditionalParametersKey = @"additionalParameters";
/*! @brief Key used to encode the @c request property for @c NSSecureCoding
*/
static NSString *const kRequestKey = @"request";
/*! @brief The exception thrown when a developer tries to create a token exchange request from an
authorization request with no authorization code.
*/
static NSString *const kTokenExchangeRequestException =
@"Attempted to create a token exchange request from an authorization response with no "
"authorization code.";
@implementation OIDAuthorizationResponse
/*! @brief Returns a mapping of incoming parameters to instance variables.
@return A mapping of incoming parameters to instance variables.
*/
+ (NSDictionary<NSString *, OIDFieldMapping *> *)fieldMap {
static NSMutableDictionary<NSString *, OIDFieldMapping *> *fieldMap;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
fieldMap = [NSMutableDictionary dictionary];
fieldMap[kStateKey] =
[[OIDFieldMapping alloc] initWithName:@"_state" type:[NSString class]];
fieldMap[kAuthorizationCodeKey] =
[[OIDFieldMapping alloc] initWithName:@"_authorizationCode" type:[NSString class]];
fieldMap[kAccessTokenKey] =
[[OIDFieldMapping alloc] initWithName:@"_accessToken" type:[NSString class]];
fieldMap[kExpiresInKey] =
[[OIDFieldMapping alloc] initWithName:@"_accessTokenExpirationDate"
type:[NSDate class]
conversion:^id _Nullable(NSObject *_Nullable value) {
if (![value isKindOfClass:[NSNumber class]]) {
return value;
}
NSNumber *valueAsNumber = (NSNumber *)value;
return [NSDate dateWithTimeIntervalSinceNow:[valueAsNumber longLongValue]];
}];
fieldMap[kTokenTypeKey] =
[[OIDFieldMapping alloc] initWithName:@"_tokenType" type:[NSString class]];
fieldMap[kIDTokenKey] =
[[OIDFieldMapping alloc] initWithName:@"_idToken" type:[NSString class]];
fieldMap[kScopeKey] =
[[OIDFieldMapping alloc] initWithName:@"_scope" type:[NSString class]];
});
return fieldMap;
}
#pragma mark - Initializers
- (instancetype)init
OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithRequest:parameters:))
- (instancetype)initWithRequest:(OIDAuthorizationRequest *)request
parameters:(NSDictionary<NSString *, NSObject<NSCopying> *> *)parameters {
self = [super init];
if (self) {
_request = [request copy];
NSDictionary<NSString *, NSObject<NSCopying> *> *additionalParameters =
[OIDFieldMapping remainingParametersWithMap:[[self class] fieldMap]
parameters:parameters
instance:self];
_additionalParameters = additionalParameters;
}
return self;
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(nullable NSZone *)zone {
// The documentation for NSCopying specifically advises us to return a reference to the original
// instance in the case where instances are immutable (as ours is):
// "Implement NSCopying by retaining the original instead of creating a new copy when the class
// and its contents are immutable."
return self;
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
OIDAuthorizationRequest *request =
[aDecoder decodeObjectOfClass:[OIDAuthorizationRequest class] forKey:kRequestKey];
self = [self initWithRequest:request parameters:@{ }];
if (self) {
[OIDFieldMapping decodeWithCoder:aDecoder map:[[self class] fieldMap] instance:self];
_additionalParameters = [aDecoder decodeObjectOfClasses:[OIDFieldMapping JSONTypes]
forKey:kAdditionalParametersKey];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:_request forKey:kRequestKey];
[OIDFieldMapping encodeWithCoder:aCoder map:[[self class] fieldMap] instance:self];
[aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey];
}
#pragma mark - NSObject overrides
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, authorizationCode: %@, state: \"%@\", accessToken: "
"\"%@\", accessTokenExpirationDate: %@, tokenType: %@, "
"idToken: \"%@\", scope: \"%@\", additionalParameters: %@, "
"request: %@>",
NSStringFromClass([self class]),
(void *)self,
_authorizationCode,
_state,
[OIDTokenUtilities redact:_accessToken],
_accessTokenExpirationDate,
_tokenType,
[OIDTokenUtilities redact:_idToken],
_scope,
_additionalParameters,
_request];
}
#pragma mark -
- (OIDTokenRequest *)tokenExchangeRequest {
return [self tokenExchangeRequestWithAdditionalParameters:nil];
}
- (OIDTokenRequest *)tokenExchangeRequestWithAdditionalParameters:
(NSDictionary<NSString *, NSString *> *)additionalParameters {
// TODO: add a unit test to confirm exception is thrown when expected and the request is created
// with the correct parameters.
if (!_authorizationCode) {
[NSException raise:kTokenExchangeRequestException
format:kTokenExchangeRequestException];
}
return [[OIDTokenRequest alloc] initWithConfiguration:_request.configuration
grantType:OIDGrantTypeAuthorizationCode
authorizationCode:_authorizationCode
redirectURL:_request.redirectURL
clientID:_request.clientID
clientSecret:_request.clientSecret
scope:nil
refreshToken:nil
codeVerifier:_request.codeVerifier
additionalParameters:additionalParameters];
}
@end
/*! @file OIDAuthorizationService.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
@class OIDAuthorization;
@class OIDAuthorizationRequest;
@class OIDAuthorizationResponse;
@class OIDEndSessionRequest;
@class OIDEndSessionResponse;
@class OIDRegistrationRequest;
@class OIDRegistrationResponse;
@class OIDServiceConfiguration;
@class OIDTokenRequest;
@class OIDTokenResponse;
@protocol OIDExternalUserAgent;
@protocol OIDExternalUserAgentSession;
NS_ASSUME_NONNULL_BEGIN
/*! @brief Represents the type of block used as a callback for creating a service configuration from
a remote OpenID Connect Discovery document.
@param configuration The service configuration, if available.
@param error The error if an error occurred.
*/
typedef void (^OIDDiscoveryCallback)(OIDServiceConfiguration *_Nullable configuration,
NSError *_Nullable error);
/*! @brief Represents the type of block used as a callback for various methods of
@c OIDAuthorizationService.
@param authorizationResponse The authorization response, if available.
@param error The error if an error occurred.
*/
typedef void (^OIDAuthorizationCallback)(OIDAuthorizationResponse *_Nullable authorizationResponse,
NSError *_Nullable error);
/*! @brief Block used as a callback for the end-session request of @c OIDAuthorizationService.
@param endSessionResponse The end-session response, if available.
@param error The error if an error occurred.
*/
typedef void (^OIDEndSessionCallback)(OIDEndSessionResponse *_Nullable endSessionResponse,
NSError *_Nullable error);
/*! @brief Represents the type of block used as a callback for various methods of
@c OIDAuthorizationService.
@param tokenResponse The token response, if available.
@param error The error if an error occurred.
*/
typedef void (^OIDTokenCallback)(OIDTokenResponse *_Nullable tokenResponse,
NSError *_Nullable error);
/*! @brief Represents the type of dictionary used to specify additional querystring parameters
when making authorization or token endpoint requests.
*/
typedef NSDictionary<NSString *, NSString *> *_Nullable OIDTokenEndpointParameters;
/*! @brief Represents the type of block used as a callback for various methods of
@c OIDAuthorizationService.
@param registrationResponse The registration response, if available.
@param error The error if an error occurred.
*/
typedef void (^OIDRegistrationCompletion)(OIDRegistrationResponse *_Nullable registrationResponse,
NSError *_Nullable error);
/*! @brief Performs various OAuth and OpenID Connect related calls via the user agent or
\NSURLSession.
*/
@interface OIDAuthorizationService : NSObject
/*! @brief The service's configuration.
@remarks Each authorization service is initialized with a configuration. This configuration
specifies how to connect to a particular OAuth provider. Clients should use separate
authorization service instances for each provider they wish to integrate with.
Configurations may be created manually, or via an OpenID Connect Discovery Document.
*/
@property(nonatomic, readonly) OIDServiceConfiguration *configuration;
/*! @internal
@brief Unavailable. This class should not be initialized.
*/
- (instancetype)init NS_UNAVAILABLE;
/*! @brief Convenience method for creating an authorization service configuration from an OpenID
Connect compliant issuer URL.
@param issuerURL The service provider's OpenID Connect issuer.
@param completion A block which will be invoked when the authorization service configuration has
been created, or when an error has occurred.
@see https://openid.net/specs/openid-connect-discovery-1_0.html
*/
+ (void)discoverServiceConfigurationForIssuer:(NSURL *)issuerURL
completion:(OIDDiscoveryCallback)completion;
/*! @brief Convenience method for creating an authorization service configuration from an OpenID
Connect compliant identity provider's discovery document.
@param discoveryURL The URL of the service provider's OpenID Connect discovery document.
@param completion A block which will be invoked when the authorization service configuration has
been created, or when an error has occurred.
@see https://openid.net/specs/openid-connect-discovery-1_0.html
*/
+ (void)discoverServiceConfigurationForDiscoveryURL:(NSURL *)discoveryURL
completion:(OIDDiscoveryCallback)completion;
/*! @brief Perform an authorization flow using a generic flow shim.
@param request The authorization request.
@param externalUserAgent Generic external user-agent that can present an authorization
request.
@param callback The method called when the request has completed or failed.
@return A @c OIDExternalUserAgentSession instance which will terminate when it
receives a @c OIDExternalUserAgentSession.cancel message, or after processing a
@c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message.
*/
+ (id<OIDExternalUserAgentSession>) presentAuthorizationRequest:(OIDAuthorizationRequest *)request
externalUserAgent:(id<OIDExternalUserAgent>)externalUserAgent
callback:(OIDAuthorizationCallback)callback;
/*! @brief Perform a logout request.
@param request The end-session logout request.
@param externalUserAgent Generic external user-agent that can present user-agent requests.
@param callback The method called when the request has completed or failed.
@return A @c OIDExternalUserAgentSession instance which will terminate when it
receives a @c OIDExternalUserAgentSession.cancel message, or after processing a
@c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message.
@see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout
*/
+ (id<OIDExternalUserAgentSession>)
presentEndSessionRequest:(OIDEndSessionRequest *)request
externalUserAgent:(id<OIDExternalUserAgent>)externalUserAgent
callback:(OIDEndSessionCallback)callback;
/*! @brief Performs a token request.
@param request The token request.
@param callback The method called when the request has completed or failed.
*/
+ (void)performTokenRequest:(OIDTokenRequest *)request callback:(OIDTokenCallback)callback;
/*! @brief Performs a token request.
@param request The token request.
@param authorizationResponse The original authorization response related to this token request.
@param callback The method called when the request has completed or failed.
*/
+ (void)performTokenRequest:(OIDTokenRequest *)request
originalAuthorizationResponse:(OIDAuthorizationResponse *_Nullable)authorizationResponse
callback:(OIDTokenCallback)callback;
/*! @brief Performs a registration request.
@param request The registration request.
@param completion The method called when the request has completed or failed.
*/
+ (void)performRegistrationRequest:(OIDRegistrationRequest *)request
completion:(OIDRegistrationCompletion)completion;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDClientMetadataParameters.h
@brief AppAuth iOS SDK
@copyright
Copyright 2016 The AppAuth for iOS Authors. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/*! @brief Parameter name for the token endpoint authentication method.
*/
extern NSString *const OIDTokenEndpointAuthenticationMethodParam;
/*! @brief Parameter name for the application type.
*/
extern NSString *const OIDApplicationTypeParam;
/*! @brief Parameter name for the redirect URI values.
*/
extern NSString *const OIDRedirectURIsParam;
/*! @brief Parameter name for the response type values.
*/
extern NSString *const OIDResponseTypesParam;
/*! @brief Parameter name for the grant type values.
*/
extern NSString *const OIDGrantTypesParam;
/*! @brief Parameter name for the subject type.
*/
extern NSString *const OIDSubjectTypeParam;
/*! @brief Application type that indicates this client is a native (not a web) application.
*/
extern NSString *const OIDApplicationTypeNative;
NS_ASSUME_NONNULL_END
/*! @file OIDClientMetadataParameters.h
@brief AppAuth iOS SDK
@copyright
Copyright 2016 The AppAuth for iOS Authors. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDClientMetadataParameters.h"
NSString *const OIDTokenEndpointAuthenticationMethodParam = @"token_endpoint_auth_method";
NSString *const OIDApplicationTypeParam = @"application_type";
NSString *const OIDRedirectURIsParam = @"redirect_uris";
NSString *const OIDResponseTypesParam = @"response_types";
NSString *const OIDGrantTypesParam = @"grant_types";
NSString *const OIDSubjectTypeParam = @"subject_type";
NSString *const OIDApplicationTypeNative = @"native";
/*! @file OIDDefines.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*! @def OIDIsEqualIncludingNil(x, y)
@brief Returns YES if x and y are equal by reference or value.
@discussion NOTE: parameters may be evaluated multiple times. Be careful if using this check
with expressions - especially if the expressions have side effects.
@param x An object.
@param y An object.
*/
#define OIDIsEqualIncludingNil(x, y) (((x) == (y)) || [(x) isEqual:(y)])
/*! @def OID_UNAVAILABLE_USE_INITIALIZER(designatedInitializer)
@brief Provides a template implementation for init-family methods which have been marked as
NS_UNAVILABLE. Stops the compiler from giving a warning when it's the super class'
designated initializer, and gives callers useful feedback telling them what the
new designated initializer is.
@remarks Takes a SEL as a parameter instead of a string so that we get compiler warnings if the
designated intializer's signature changes.
@param designatedInitializer A SEL referencing the designated initializer.
*/
#define OID_UNAVAILABLE_USE_INITIALIZER(designatedInitializer) { \
NSString *reason = [NSString stringWithFormat:@"Called: %@\nDesignated Initializer:%@", \
NSStringFromSelector(_cmd), \
NSStringFromSelector(designatedInitializer)]; \
@throw [NSException exceptionWithName:@"Attempt to call unavailable initializer." \
reason:reason \
userInfo:nil]; \
}
#ifdef _APPAUTHTRACE
# define AppAuthRequestTrace(fmt, ...) NSLog(fmt, ##__VA_ARGS__);
#else // _APPAUTHTRACE
# define AppAuthRequestTrace(...)
#endif // _APPAUTHTRACE
/*! @file OIDEndSessionRequest.h
@brief AppAuth iOS SDK
@copyright
Copyright 2017 The AppAuth Authors. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
#import "OIDExternalUserAgentRequest.h"
@class OIDServiceConfiguration;
NS_ASSUME_NONNULL_BEGIN
@interface OIDEndSessionRequest : NSObject
<NSCopying, NSSecureCoding, OIDExternalUserAgentRequest>
/*! @brief The service's configuration.
@remarks This configuration specifies how to connect to a particular OAuth provider.
Configurations may be created manually, or via an OpenID Connect Discovery Document.
*/
@property(nonatomic, readonly) OIDServiceConfiguration *configuration;
/*! @brief The client's redirect URI.
@remarks post_logout_redirect_uri
@see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout
*/
@property(nonatomic, readonly, nullable) NSURL *postLogoutRedirectURL;
/*! @brief Previously issued ID Token passed to the end session endpoint as a hint about the End-User's current authenticated
session with the Client
@remarks id_token_hint
@see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout
*/
@property(nonatomic, readonly, nullable) NSString *idTokenHint;
/*! @brief An opaque value used by the client to maintain state between the request and callback.
@remarks state
@discussion If this value is not explicitly set, this library will automatically add state and
perform appropriate validation of the state in the authorization response. It is recommended
that the default implementation of this parameter be used wherever possible. Typically used
to prevent CSRF attacks, as recommended in RFC6819 Section 5.3.5.
@see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout
*/
@property(nonatomic, readonly, nullable) NSString *state;
/*! @brief The client's additional authorization parameters.
@see https://tools.ietf.org/html/rfc6749#section-3.1
*/
@property(nonatomic, readonly, nullable) NSDictionary<NSString *, NSString *> *additionalParameters;
/*! @internal
@brief Unavailable. Please use @c initWithConfiguration:clientId:scopes:redirectURL:additionalParameters:.
*/
- (instancetype)init NS_UNAVAILABLE;
/*! @brief Creates an authorization request with opinionated defaults (a secure @c state).
@param configuration The service's configuration.
@param idTokenHint The previously issued ID Token
@param postLogoutRedirectURL The client's post-logout redirect URI.
callback.
@param additionalParameters The client's additional authorization parameters.
*/
- (instancetype)
initWithConfiguration:(OIDServiceConfiguration *)configuration
idTokenHint:(NSString *)idTokenHint
postLogoutRedirectURL:(NSURL *)postLogoutRedirectURL
additionalParameters:(nullable NSDictionary<NSString *, NSString *> *)additionalParameters;
/*! @brief Designated initializer.
@param configuration The service's configuration.
@param idTokenHint The previously issued ID Token
@param postLogoutRedirectURL The client's post-logout redirect URI.
@param state An opaque value used by the client to maintain state between the request and
callback.
@param additionalParameters The client's additional authorization parameters.
*/
- (instancetype)
initWithConfiguration:(OIDServiceConfiguration *)configuration
idTokenHint:(NSString *)idTokenHint
postLogoutRedirectURL:(NSURL *)postLogoutRedirectURL
state:(NSString *)state
additionalParameters:(nullable NSDictionary<NSString *, NSString *> *)additionalParameters
NS_DESIGNATED_INITIALIZER;
/*! @brief Constructs the request URI by adding the request parameters to the query component of the
authorization endpoint URI using the "application/x-www-form-urlencoded" format.
@return A URL representing the authorization request.
@see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout
*/
- (NSURL *)endSessionRequestURL;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDEndSessionRequest.m
@brief AppAuth iOS SDK
@copyright
Copyright 2017 The AppAuth Authors. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDEndSessionRequest.h"
#import "OIDDefines.h"
#import "OIDTokenUtilities.h"
#import "OIDServiceConfiguration.h"
#import "OIDServiceDiscovery.h"
#import "OIDURLQueryComponent.h"
/*! @brief The key for the @c configuration property for @c NSSecureCoding
*/
static NSString *const kConfigurationKey = @"configuration";
/*! @brief Key used to encode the @c state property for @c NSSecureCoding, and on the URL request.
*/
static NSString *const kStateKey = @"state";
/*! @brief Key used to encode the @c postLogoutRedirectURL property for @c NSSecureCoding, and on the URL request.
*/
static NSString *const kPostLogoutRedirectURLKey = @"post_logout_redirect_uri";
/*! @brief Key used to encode the @c idTokenHint property for @c NSSecureCoding, and on the URL request.
*/
static NSString *const kIdTokenHintKey = @"id_token_hint";
/*! @brief Key used to encode the @c additionalParameters property for @c NSSecureCoding
*/
static NSString *const kAdditionalParametersKey = @"additionalParameters";
/*! @brief Number of random bytes generated for the @state.
*/
static NSUInteger const kStateSizeBytes = 32;
/*! @brief Assertion text for missing end_session_endpoint.
*/
static NSString *const OIDMissingEndSessionEndpointMessage =
@"The service configuration is missing an end_session_endpoint.";
@implementation OIDEndSessionRequest
- (instancetype)init
OID_UNAVAILABLE_USE_INITIALIZER(
@selector(initWithConfiguration:
idTokenHint:
postLogoutRedirectURL:
additionalParameters:)
)
- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration
idTokenHint:(NSString *)idTokenHint
postLogoutRedirectURL:(NSURL *)postLogoutRedirectURL
state:(NSString *)state
additionalParameters:(NSDictionary<NSString *,NSString *> *)additionalParameters
{
self = [super init];
if (self) {
_configuration = [configuration copy];
_idTokenHint = [idTokenHint copy];
_postLogoutRedirectURL = [postLogoutRedirectURL copy];
_state = [state copy];
_additionalParameters =
[[NSDictionary alloc] initWithDictionary:additionalParameters copyItems:YES];
}
return self;
}
- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration
idTokenHint:(NSString *)idTokenHint
postLogoutRedirectURL:(NSURL *)postLogoutRedirectURL
additionalParameters:(NSDictionary<NSString *,NSString *> *)additionalParameters
{
return [self initWithConfiguration:configuration
idTokenHint:idTokenHint
postLogoutRedirectURL:postLogoutRedirectURL
state:[[self class] generateState]
additionalParameters:additionalParameters];
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(nullable NSZone *)zone {
// The documentation for NSCopying specifically advises us to return a reference to the original
// instance in the case where instances are immutable (as ours is):
// "Implement NSCopying by retaining the original instead of creating a new copy when the class
// and its contents are immutable."
return self;
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
OIDServiceConfiguration *configuration = [aDecoder decodeObjectOfClass:[OIDServiceConfiguration class] forKey:kConfigurationKey];
NSString *idTokenHint = [aDecoder decodeObjectOfClass:[NSString class] forKey:kIdTokenHintKey];
NSURL *postLogoutRedirectURL = [aDecoder decodeObjectOfClass:[NSURL class] forKey:kPostLogoutRedirectURLKey];
NSString *state = [aDecoder decodeObjectOfClass:[NSString class] forKey:kStateKey];
NSSet *additionalParameterCodingClasses = [NSSet setWithArray:@[
[NSDictionary class],
[NSString class]
]];
NSDictionary *additionalParameters = [aDecoder decodeObjectOfClasses:additionalParameterCodingClasses
forKey:kAdditionalParametersKey];
self = [self initWithConfiguration:configuration
idTokenHint:idTokenHint
postLogoutRedirectURL:postLogoutRedirectURL
state:state
additionalParameters:additionalParameters];
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:_configuration forKey:kConfigurationKey];
[aCoder encodeObject:_idTokenHint forKey:kIdTokenHintKey];
[aCoder encodeObject:_postLogoutRedirectURL forKey:kPostLogoutRedirectURLKey];
[aCoder encodeObject:_state forKey:kStateKey];
[aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey];
}
#pragma mark - NSObject overrides
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, request: %@>",
NSStringFromClass([self class]),
(void *)self,
self.endSessionRequestURL];
}
+ (nullable NSString *)generateState {
return [OIDTokenUtilities randomURLSafeStringWithSize:kStateSizeBytes];
}
#pragma mark - OIDExternalUserAgentRequest
- (NSURL*)externalUserAgentRequestURL {
return [self endSessionRequestURL];
}
- (NSString *)redirectScheme {
return [_postLogoutRedirectURL scheme];
}
#pragma mark -
- (NSURL *)endSessionRequestURL {
OIDURLQueryComponent *query = [[OIDURLQueryComponent alloc] init];
// Add any additional parameters the client has specified.
[query addParameters:_additionalParameters];
// Add optional parameters, as applicable.
if (_idTokenHint) {
[query addParameter:kIdTokenHintKey value:_idTokenHint];
}
if (_postLogoutRedirectURL) {
[query addParameter:kPostLogoutRedirectURLKey value:_postLogoutRedirectURL.absoluteString];
}
if (_state) {
[query addParameter:kStateKey value:_state];
}
NSAssert(_configuration.endSessionEndpoint, OIDMissingEndSessionEndpointMessage);
// Construct the URL
return [query URLByReplacingQueryInURL:_configuration.endSessionEndpoint];
}
@end
/*! @file OIDEndSessionResponse.h
@brief AppAuth iOS SDK
@copyright
Copyright 2017 The AppAuth Authors. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
@class OIDEndSessionRequest;
NS_ASSUME_NONNULL_BEGIN
/*! @brief Represents the response to an End Session request.
@see http://openid.net/specs/openid-connect-session-1_0.html#RPLogout
*/
@interface OIDEndSessionResponse : NSObject <NSCopying, NSSecureCoding>
/*! @brief The request which was serviced.
*/
@property(nonatomic, readonly) OIDEndSessionRequest *request;
/*! @brief REQUIRED if the "state" parameter was present in the client end-session request. The
exact value received from the client.
@remarks state
*/
@property(nonatomic, readonly, nullable) NSString *state;
/*! @brief Additional parameters returned from the end session endpoint.
*/
@property(nonatomic, readonly, nullable)
NSDictionary<NSString *, NSObject<NSCopying> *> *additionalParameters;
/*! @internal
@brief Unavailable. Please use initWithParameters:.
*/
- (instancetype)init NS_UNAVAILABLE;
/*! @brief Designated initializer.
@param request The serviced request.
@param parameters The decoded parameters returned from the End Session Endpoint.
@remarks Known parameters are extracted from the @c parameters parameter and the normative
properties are populated. Non-normative parameters are placed in the
@c #additionalParameters dictionary.
*/
- (instancetype)initWithRequest:(OIDEndSessionRequest *)request
parameters:(NSDictionary<NSString *, NSObject<NSCopying> *> *)parameters
NS_DESIGNATED_INITIALIZER;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDEndSessionResponse.m
@brief AppAuth iOS SDK
@copyright
Copyright 2017 The AppAuth Authors. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDEndSessionResponse.h"
#import "OIDDefines.h"
#import "OIDEndSessionRequest.h"
#import "OIDFieldMapping.h"
/*! @brief The key for the @c state property in the incoming parameters and for @c NSSecureCoding.
*/
static NSString *const kStateKey = @"state";
/*! @brief Key used to encode the @c request property for @c NSSecureCoding
*/
static NSString *const kRequestKey = @"request";
/*! @brief Key used to encode the @c additionalParameters property for
@c NSSecureCoding
*/
static NSString *const kAdditionalParametersKey = @"additionalParameters";
@implementation OIDEndSessionResponse
#pragma mark - Initializers
- (instancetype)init
OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithRequest:parameters:))
- (instancetype)initWithRequest:(OIDEndSessionRequest *)request
parameters:(NSDictionary<NSString *,NSObject<NSCopying> *> *)parameters {
self = [super init];
if (self) {
_request = [request copy];
NSDictionary<NSString *, NSObject<NSCopying> *> *additionalParameters =
[OIDFieldMapping remainingParametersWithMap:[[self class] fieldMap]
parameters:parameters
instance:self];
_additionalParameters = additionalParameters;
}
return self;
}
/*! @brief Returns a mapping of incoming parameters to instance variables.
@return A mapping of incoming parameters to instance variables.
*/
+ (NSDictionary<NSString *, OIDFieldMapping *> *)fieldMap {
static NSMutableDictionary<NSString *, OIDFieldMapping *> *fieldMap;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
fieldMap = [NSMutableDictionary dictionary];
fieldMap[kStateKey] =
[[OIDFieldMapping alloc] initWithName:@"_state" type:[NSString class]];
});
return fieldMap;
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(nullable NSZone *)zone {
// The documentation for NSCopying specifically advises us to return a reference to the original
// instance in the case where instances are immutable (as ours is):
// "Implement NSCopying by retaining the original instead of creating a new copy when the class
// and its contents are immutable."
return self;
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
OIDEndSessionRequest *request =
[aDecoder decodeObjectOfClass:[OIDEndSessionRequest class] forKey:kRequestKey];
self = [self initWithRequest:request parameters:@{ }];
if (self) {
[OIDFieldMapping decodeWithCoder:aDecoder map:[[self class] fieldMap] instance:self];
_additionalParameters = [aDecoder decodeObjectOfClasses:[OIDFieldMapping JSONTypes]
forKey:kAdditionalParametersKey];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:_request forKey:kRequestKey];
[OIDFieldMapping encodeWithCoder:aCoder map:[[self class] fieldMap] instance:self];
[aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey];
}
#pragma mark - NSObject overrides
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, state: \"%@\", "
"additionalParameters: %@, request: %@>",
NSStringFromClass([self class]),
(void *)self,
_state,
_additionalParameters,
_request];
}
@end
/*! @file OIDError.m
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDError.h"
NSString *const OIDGeneralErrorDomain = @"org.openid.appauth.general";
NSString *const OIDOAuthTokenErrorDomain = @"org.openid.appauth.oauth_token";
NSString *const OIDOAuthAuthorizationErrorDomain = @"org.openid.appauth.oauth_authorization";
NSString *const OIDOAuthRegistrationErrorDomain = @"org.openid.appauth.oauth_registration";
NSString *const OIDResourceServerAuthorizationErrorDomain = @"org.openid.appauth.resourceserver";
NSString *const OIDHTTPErrorDomain = @"org.openid.appauth.remote-http";
NSString *const OIDOAuthExceptionInvalidAuthorizationFlow = @"An OAuth redirect was sent to a "
"OIDExternalUserAgentSession after it already completed.";
NSString *const OIDOAuthExceptionInvalidTokenRequestNullRedirectURL = @"A OIDTokenRequest was "
"created with a grant_type that requires a redirectURL, but a null redirectURL was given";
NSString *const OIDOAuthErrorResponseErrorKey = @"OIDOAuthErrorResponseErrorKey";
NSString *const OIDOAuthErrorFieldError = @"error";
NSString *const OIDOAuthErrorFieldErrorDescription = @"error_description";
NSString *const OIDOAuthErrorFieldErrorURI = @"error_uri";
/*! @file OIDErrorUtilities.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
#import "OIDError.h"
NS_ASSUME_NONNULL_BEGIN
/*! @brief Convenience methods for creating standardized \NSError instances.
*/
@interface OIDErrorUtilities : NSObject
/*! @brief Creates a standard \NSError from an @c ::OIDErrorCode and custom user info.
Automatically populates the localized error description.
@param code The error code.
@param underlyingError The underlying error which occurred, if applicable.
@param description A custom description, if applicable.
@return An \NSError representing the error code.
*/
+ (NSError *)errorWithCode:(OIDErrorCode)code
underlyingError:(nullable NSError *)underlyingError
description:(nullable NSString *)description;
/*! @brief Creates a standard \NSError from an @c ::OIDErrorCode and custom user info.
Automatically populates the localized error description.
@param OAuthErrorDomain The OAuth error domain. Must be @c ::OIDOAuthAuthorizationErrorDomain or
@c ::OIDOAuthTokenErrorDomain.
@param errorResponse The dictionary from an OAuth error response (as per RFC6749 Section 5.2).
@param underlyingError The underlying error which occurred, if applicable.
@return An \NSError representing the OAuth error.
@see https://tools.ietf.org/html/rfc6749#section-5.2
*/
+ (NSError *)OAuthErrorWithDomain:(NSString *)OAuthErrorDomain
OAuthResponse:(NSDictionary *)errorResponse
underlyingError:(nullable NSError *)underlyingError;
/*! @brief Creates a \NSError indicating that the resource server responded with an authorization
error.
@param code Your error code.
@param errorResponse The resource server error response, if any.
@param underlyingError The underlying error which occurred, if applicable.
@return An \NSError representing the authorization error from the resource server.
*/
+ (NSError *)resourceServerAuthorizationErrorWithCode:(NSInteger)code
errorResponse:(nullable NSDictionary *)errorResponse
underlyingError:(nullable NSError *)underlyingError;
/*! @brief Creates a standard \NSError from an \NSHTTPURLResponse. Automatically
populates the localized error description with the response data associated with the
\NSHTTPURLResponse, if available.
@param HTTPURLResponse The response which indicates an error occurred.
@param data The response data associated with the response which should be converted to an
@c NSString assuming a UTF-8 encoding, if available.
@return An \NSError representing the error.
*/
+ (NSError *)HTTPErrorWithHTTPResponse:(NSHTTPURLResponse *)HTTPURLResponse
data:(nullable NSData *)data;
/*! @brief Raises an exception with the given name as both the name, and the message.
@param name The name of the exception.
*/
+ (void)raiseException:(NSString *)name;
/*! @brief Raises an exception with the given name and message.
@param name The name of the exception.
@param message The message of the exception.
*/
+ (void)raiseException:(NSString *)name message:(NSString *)message;
/*! @brief Converts an OAuth error code into an @c ::OIDErrorCodeOAuth error code.
@param errorCode The OAuth error code.
@discussion Returns @c ::OIDErrorCodeOAuthOther if the string is not in AppAuth's list.
@see https://tools.ietf.org/html/rfc6749#section-4.1.2.1
@see https://tools.ietf.org/html/rfc6749#section-5.2
*/
+ (OIDErrorCodeOAuth)OAuthErrorCodeFromString:(NSString *)errorCode;
/*! @brief Returns true if the given error domain is an OAuth error domain.
@param errorDomain The error domain to test.
@discussion An OAuth error domain is used for errors returned per RFC6749 sections 4.1.2.1 and
5.2. Other errors, such as network errors can also occur but they will not have an OAuth
error domain.
@see https://tools.ietf.org/html/rfc6749#section-4.1.2.1
@see https://tools.ietf.org/html/rfc6749#section-5.2
*/
+ (BOOL)isOAuthErrorDomain:(NSString*)errorDomain;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDErrorUtilities.m
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDErrorUtilities.h"
@implementation OIDErrorUtilities
+ (NSError *)errorWithCode:(OIDErrorCode)code
underlyingError:(NSError *)underlyingError
description:(NSString *)description {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if (underlyingError) {
userInfo[NSUnderlyingErrorKey] = underlyingError;
}
if (description) {
userInfo[NSLocalizedDescriptionKey] = description;
}
// TODO: Populate localized description based on code.
NSError *error = [NSError errorWithDomain:OIDGeneralErrorDomain
code:code
userInfo:userInfo];
return error;
}
+ (BOOL)isOAuthErrorDomain:(NSString *)errorDomain {
return errorDomain == OIDOAuthRegistrationErrorDomain
|| errorDomain == OIDOAuthAuthorizationErrorDomain
|| errorDomain == OIDOAuthTokenErrorDomain;
}
+ (NSError *)resourceServerAuthorizationErrorWithCode:(NSInteger)code
errorResponse:(nullable NSDictionary *)errorResponse
underlyingError:(nullable NSError *)underlyingError {
// builds the userInfo dictionary with the full OAuth response and other information
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if (errorResponse) {
userInfo[OIDOAuthErrorResponseErrorKey] = errorResponse;
}
if (underlyingError) {
userInfo[NSUnderlyingErrorKey] = underlyingError;
}
NSError *error = [NSError errorWithDomain:OIDResourceServerAuthorizationErrorDomain
code:code
userInfo:userInfo];
return error;
}
+ (NSError *)OAuthErrorWithDomain:(NSString *)oAuthErrorDomain
OAuthResponse:(NSDictionary *)errorResponse
underlyingError:(NSError *)underlyingError {
// not a valid OAuth error
if (![self isOAuthErrorDomain:oAuthErrorDomain]
|| !errorResponse
|| !errorResponse[OIDOAuthErrorFieldError]
|| ![errorResponse[OIDOAuthErrorFieldError] isKindOfClass:[NSString class]]) {
return [[self class] errorWithCode:OIDErrorCodeNetworkError
underlyingError:underlyingError
description:underlyingError.localizedDescription];
}
// builds the userInfo dictionary with the full OAuth response and other information
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
userInfo[OIDOAuthErrorResponseErrorKey] = errorResponse;
if (underlyingError) {
userInfo[NSUnderlyingErrorKey] = underlyingError;
}
NSString *oauthErrorCodeString = errorResponse[OIDOAuthErrorFieldError];
NSString *oauthErrorMessage = nil;
if ([errorResponse[OIDOAuthErrorFieldErrorDescription] isKindOfClass:[NSString class]]) {
oauthErrorMessage = errorResponse[OIDOAuthErrorFieldErrorDescription];
} else {
oauthErrorMessage = [errorResponse[OIDOAuthErrorFieldErrorDescription] description];
}
NSString *oauthErrorURI = nil;
if ([errorResponse[OIDOAuthErrorFieldErrorURI] isKindOfClass:[NSString class]]) {
oauthErrorURI = errorResponse[OIDOAuthErrorFieldErrorURI];
} else {
oauthErrorURI = [errorResponse[OIDOAuthErrorFieldErrorURI] description];
}
// builds the error description, using the information supplied by the server if possible
NSMutableString *description = [NSMutableString string];
[description appendString:oauthErrorCodeString];
if (oauthErrorMessage) {
[description appendString:@": "];
[description appendString:oauthErrorMessage];
}
if (oauthErrorURI) {
if ([description length] > 0) {
[description appendString:@" - "];
}
[description appendString:oauthErrorURI];
}
if ([description length] == 0) {
// backup description
[description appendFormat:@"OAuth error: %@ - https://tools.ietf.org/html/rfc6749#section-5.2",
oauthErrorCodeString];
}
userInfo[NSLocalizedDescriptionKey] = description;
// looks up the error code based on the "error" response param
OIDErrorCodeOAuth code = [[self class] OAuthErrorCodeFromString:oauthErrorCodeString];
NSError *error = [NSError errorWithDomain:oAuthErrorDomain
code:code
userInfo:userInfo];
return error;
}
+ (NSError *)HTTPErrorWithHTTPResponse:(NSHTTPURLResponse *)HTTPURLResponse
data:(nullable NSData *)data {
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if (data) {
NSString *serverResponse =
[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (serverResponse) {
userInfo[NSLocalizedDescriptionKey] = serverResponse;
}
}
NSError *serverError =
[NSError errorWithDomain:OIDHTTPErrorDomain
code:HTTPURLResponse.statusCode
userInfo:userInfo];
return serverError;
}
+ (OIDErrorCodeOAuth)OAuthErrorCodeFromString:(NSString *)errorCode {
NSDictionary *errorCodes = @{
@"invalid_request": @(OIDErrorCodeOAuthInvalidRequest),
@"unauthorized_client": @(OIDErrorCodeOAuthUnauthorizedClient),
@"access_denied": @(OIDErrorCodeOAuthAccessDenied),
@"unsupported_response_type": @(OIDErrorCodeOAuthUnsupportedResponseType),
@"invalid_scope": @(OIDErrorCodeOAuthInvalidScope),
@"server_error": @(OIDErrorCodeOAuthServerError),
@"temporarily_unavailable": @(OIDErrorCodeOAuthTemporarilyUnavailable),
@"invalid_client": @(OIDErrorCodeOAuthInvalidClient),
@"invalid_grant": @(OIDErrorCodeOAuthInvalidGrant),
@"unsupported_grant_type": @(OIDErrorCodeOAuthUnsupportedGrantType),
};
NSNumber *code = errorCodes[errorCode];
if (code) {
return [code integerValue];
} else {
return OIDErrorCodeOAuthOther;
}
}
+ (void)raiseException:(NSString *)name {
[[self class] raiseException:name message:name];
}
+ (void)raiseException:(NSString *)name message:(NSString *)message {
[NSException raise:name format:@"%@", message];
}
@end
/*! @file OIDExternalUserAgent.h
@brief AppAuth iOS SDK
@copyright
Copyright 2016 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
@protocol OIDExternalUserAgentSession;
@protocol OIDExternalUserAgentRequest;
NS_ASSUME_NONNULL_BEGIN
/*! @protocol OIDExternalUserAgent
@brief An external user-agent UI that presents displays the request to the user. Clients may
provide custom implementations of an external user-agent to customize the way the requests
are presented to the end user.
*/
@protocol OIDExternalUserAgent<NSObject>
/*! @brief Presents the request in the external user-agent.
@param request The request to be presented in the external user-agent.
@param session The @c OIDExternalUserAgentSession instance that initiates presenting the UI.
Concrete implementations of a @c OIDExternalUserAgent may call
resumeExternalUserAgentFlowWithURL or failExternalUserAgentFlowWithError on session to either
resume or fail the request.
@return YES If the request UI was successfully presented to the user.
*/
- (BOOL)presentExternalUserAgentRequest:(id<OIDExternalUserAgentRequest> )request
session:(id<OIDExternalUserAgentSession>)session;
/*! @brief Dimisses the external user-agent and calls completion when the dismiss operation ends.
@param animated Whether or not the dismiss operation should be animated.
@remarks Has no effect if no UI is presented.
@param completion The block to be called when the dismiss operations ends
*/
- (void)dismissExternalUserAgentAnimated:(BOOL)animated completion:(void (^)(void))completion;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDExternalUserAgent.h
@brief AppAuth iOS SDK
@copyright
Copyright 2017 The AppAuth Authors. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*! @protocol OIDExternalUserAgent
@brief An interface that any external user-agent request may implement to use the
@c OIDExternalUserAgent flow.
*/
@protocol OIDExternalUserAgentRequest
/*! @brief Method to create and return the complete request URL instance.
@return A @c NSURL instance which contains the URL to be opened in an external UI (i.e. browser)
*/
- (NSURL*)externalUserAgentRequestURL;
/*! @brief If this external user-agent request has a redirect URL, this should return its scheme.
Since some external requests have optional callbacks (such as the end session endpoint), the
return value of this method is nullable.
@return A @c NSString instance that contains the scheme of a callback url, or nil if there is
no callback url for this request.
*/
- (NSString*)redirectScheme;
@end
/*! @file OIDExternalUserAgentSession.h
@brief AppAuth iOS SDK
@copyright
Copyright 2017 The AppAuth Authors. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
NS_ASSUME_NONNULL_BEGIN
/*! @brief Represents an in-flight external user-agent session.
*/
@protocol OIDExternalUserAgentSession <NSObject>
/*! @brief Cancels the code flow session, invoking the request's callback with a cancelled error.
@remarks Has no effect if called more than once, or after a
@c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message was received.
Will cause an error with code: @c ::OIDErrorCodeProgramCanceledAuthorizationFlow to be
passed to the @c callback block passed to
@c OIDAuthorizationService.presentAuthorizationRequest:presentingViewController:callback:
*/
- (void)cancel;
/*! @brief Cancels the code flow session, invoking the request's callback with a cancelled error.
@remarks Has no effect if called more than once, or after a
@c OIDExternalUserAgentSession.resumeExternalUserAgentFlowWithURL: message was received.
Will cause an error with code: @c ::OIDErrorCodeProgramCanceledAuthorizationFlow to be
passed to the @c callback block passed to
@c OIDAuthorizationService.presentAuthorizationRequest:presentingViewController:callback:
@param completion The block to be called when the cancel operation ends
*/
- (void)cancelWithCompletion:(nullable void (^)(void))completion;
/*! @brief Clients should call this method with the result of the external user-agent code flow if
it becomes available.
@param URL The redirect URL invoked by the server.
@discussion When the URL represented a valid response, implementations should clean up any
left-over UI state from the request, for example by closing the
\SFSafariViewController or loopback HTTP listener if those were used. The completion block
of the pending request should then be invoked.
@remarks Has no effect if called more than once, or after a @c cancel message was received.
@return YES if the passed URL matches the expected redirect URL and was consumed, NO otherwise.
*/
- (BOOL)resumeExternalUserAgentFlowWithURL:(NSURL *)URL;
/*! @brief @c OIDExternalUserAgent or clients should call this method when the
external user-agent flow failed with a non-OAuth error.
@param error The error that is the reason for the failure of this external flow.
@remarks Has no effect if called more than once, or after a @c cancel message was received.
*/
- (void)failExternalUserAgentFlowWithError:(NSError *)error;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDFieldMapping.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/*! @brief Represents a function which transforms incoming source values into instance variable
values.
*/
typedef _Nullable id(^OIDFieldMappingConversionFunction)(NSObject *_Nullable value);
/*! @brief Describes the mapping of a key/value pair to an iVar with an optional conversion
function.
*/
@interface OIDFieldMapping : NSObject
/*! @brief The name of the instance variable the field should be mapped to.
*/
@property(nonatomic, readonly) NSString *name;
/*! @brief The type of the instance variable.
*/
@property(nonatomic, readonly) Class expectedType;
/*! @brief An optional conversion function which specifies a transform from the incoming data to the
instance variable value.
*/
@property(nonatomic, readonly, nullable) OIDFieldMappingConversionFunction conversion;
/*! @internal
@brief Unavailable. Please use initWithName:type:conversion:.
*/
- (instancetype)init NS_UNAVAILABLE;
/*! @brief The designated initializer.
@param name The name of the instance variable the field should be mapped to.
@param type The type of the instance variable.
@param conversion An optional conversion function which specifies a transform from the incoming
data to the instance variable value. Used during the process performed by
@c OIDFieldMapping.remainingParametersWithMap:parameters:instance: but not during
encoding/decoding, since the encoded and decoded values should already be of the type
specified by the @c type parameter.
*/
- (instancetype)initWithName:(NSString *)name
type:(Class)type
conversion:(nullable OIDFieldMappingConversionFunction)conversion
NS_DESIGNATED_INITIALIZER;
/*! @brief A convenience initializer.
@param name The name of the instance variable the field should be mapped to.
@param type The type of the instance variable.
*/
- (instancetype)initWithName:(NSString *)name
type:(Class)type;
/*! @brief Performs a mapping of key/value pairs in an incoming parameters dictionary to instance
variables, returning a dictionary of parameter key/values which didn't map to instance
variables.
@param map A mapping of incoming keys to instance variables.
@param parameters Incoming key value pairs to map to an instance's variables.
@param instance The instance whose variables should be set based on the mapping.
@return A dictionary of parameter key/values which didn't map to instance variables.
*/
+ (NSDictionary<NSString *, NSObject<NSCopying> *> *)remainingParametersWithMap:
(NSDictionary<NSString *, OIDFieldMapping *> *)map
parameters:(NSDictionary<NSString *, NSObject<NSCopying> *> *)parameters
instance:(id)instance;
/*! @brief This helper method for @c NSCoding implementations performs a serialization of fields
defined in a field mapping.
@param aCoder An @c NSCoder instance to serialize instance variable values to.
@param map A mapping of keys to instance variables.
@param instance The instance whose variables should be serialized based on the mapping.
*/
+ (void)encodeWithCoder:(NSCoder *)aCoder
map:(NSDictionary<NSString *, OIDFieldMapping *> *)map
instance:(id)instance;
/*! @brief This helper method for @c NSCoding implementations performs a deserialization of
fields defined in a field mapping.
@param aCoder An @c NSCoder instance from which to deserialize instance variable values from.
@param map A mapping of keys to instance variables.
@param instance The instance whose variables should be deserialized based on the mapping.
*/
+ (void)decodeWithCoder:(NSCoder *)aCoder
map:(NSDictionary<NSString *, OIDFieldMapping *> *)map
instance:(id)instance;
/*! @brief Returns an @c NSSet of classes suitable for deserializing JSON content in an
@c NSSecureCoding context.
*/
+ (NSSet *)JSONTypes;
/*! @brief Returns a function for converting an @c NSString to an @c NSURL.
*/
+ (OIDFieldMappingConversionFunction)URLConversion;
/*! @brief Returns a function for converting an @c NSNumber number of seconds from now to an
@c NSDate.
*/
+ (OIDFieldMappingConversionFunction)dateSinceNowConversion;
/*! @brief Returns a function for converting an @c NSNumber representing a unix time stamp to an
@c NSDate.
*/
+ (OIDFieldMappingConversionFunction)dateEpochConversion;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDFieldMapping.m
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDFieldMapping.h"
#import "OIDDefines.h"
@implementation OIDFieldMapping
- (nonnull instancetype)init
OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithName:type:conversion:))
- (instancetype)initWithName:(NSString *)name
type:(Class)type {
return [self initWithName:name type:type conversion:nil];
}
- (instancetype)initWithName:(NSString *)name
type:(Class)type
conversion:(nullable OIDFieldMappingConversionFunction)conversion {
self = [super init];
if (self) {
_name = [name copy];
_expectedType = type;
_conversion = conversion;
}
return self;
}
+ (NSDictionary<NSString *, NSObject<NSCopying> *> *)remainingParametersWithMap:
(NSDictionary<NSString *, OIDFieldMapping *> *)map
parameters:(NSDictionary<NSString *, NSObject<NSCopying> *> *)parameters
instance:(id)instance {
NSMutableDictionary *additionalParameters = [NSMutableDictionary dictionary];
for (NSString *key in parameters) {
NSObject<NSCopying> *value = [parameters[key] copy];
OIDFieldMapping *mapping = map[key];
// If the field doesn't appear in the mapping, we add it to the additional parameters
// dictionary.
if (!mapping) {
additionalParameters[key] = value;
continue;
}
// If the field mapping specifies a conversion function, apply the conversion to the value.
if (mapping.conversion) {
value = mapping.conversion(value);
}
// Check the type of the value and make sure it matches the type we expected. If it doesn't we
// add the value to the additional parameters dictionary but don't assign the instance variable.
if (![value isKindOfClass:mapping.expectedType]) {
additionalParameters[key] = value;
continue;
}
// Assign the instance variable.
[instance setValue:value forKey:mapping.name];
}
return additionalParameters;
}
+ (void)encodeWithCoder:(NSCoder *)aCoder
map:(NSDictionary<NSString *, OIDFieldMapping *> *)map
instance:(id)instance {
for (NSString *key in map) {
id value = [instance valueForKey:map[key].name];
[aCoder encodeObject:value forKey:key];
}
}
+ (void)decodeWithCoder:(NSCoder *)aCoder
map:(NSDictionary<NSString *, OIDFieldMapping *> *)map
instance:(id)instance {
for (NSString *key in map) {
OIDFieldMapping *mapping = map[key];
id value = [aCoder decodeObjectOfClass:mapping.expectedType forKey:key];
[instance setValue:value forKey:mapping.name];
}
}
+ (NSSet *)JSONTypes {
return [NSSet setWithArray:@[
[NSDictionary class],
[NSArray class],
[NSString class],
[NSNumber class]
]];
}
+ (OIDFieldMappingConversionFunction)URLConversion {
return ^id _Nullable(NSObject *_Nullable value) {
if ([value isKindOfClass:[NSString class]]) {
return [NSURL URLWithString:(NSString *)value];
}
return value;
};
}
+ (OIDFieldMappingConversionFunction)dateSinceNowConversion {
return ^id _Nullable(NSObject *_Nullable value) {
if (![value isKindOfClass:[NSNumber class]]) {
return value;
}
NSNumber *valueAsNumber = (NSNumber *)value;
return [NSDate dateWithTimeIntervalSinceNow:[valueAsNumber longLongValue]];
};
}
+ (OIDFieldMappingConversionFunction)dateEpochConversion {
return ^id _Nullable(NSObject *_Nullable value) {
if (![value isKindOfClass:[NSNumber class]]) {
return value;
}
NSNumber *valueAsNumber = (NSNumber *) value;
return [NSDate dateWithTimeIntervalSince1970:[valueAsNumber longLongValue]];
};
}
@end
/*! @file OIDGrantTypes.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
/*! @brief For exchanging an authorization code for an access token.
@see https://tools.ietf.org/html/rfc6749#section-4.1.3
*/
extern NSString *const OIDGrantTypeAuthorizationCode;
/*! @brief For refreshing an access token with a refresh token.
@see https://tools.ietf.org/html/rfc6749#section-6
*/
extern NSString *const OIDGrantTypeRefreshToken;
/*! @brief For obtaining an access token with a username and password.
@see https://tools.ietf.org/html/rfc6749#section-4.3.2
*/
extern NSString *const OIDGrantTypePassword;
/*! @brief For obtaining an access token from the token endpoint using client credentials.
@see https://tools.ietf.org/html/rfc6749#section-3.2.1
@see https://tools.ietf.org/html/rfc6749#section-4.4.2
*/
extern NSString *const OIDGrantTypeClientCredentials;
/*! @file OIDGrantTypes.m
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDGrantTypes.h"
NSString *const OIDGrantTypeAuthorizationCode = @"authorization_code";
NSString *const OIDGrantTypeRefreshToken = @"refresh_token";
NSString *const OIDGrantTypePassword = @"password";
NSString *const OIDGrantTypeClientCredentials = @"client_credentials";
/*! @file OIDIDToken.h
@brief AppAuth iOS SDK
@copyright
Copyright 2017 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/*! @brief A convenience class that parses an ID Token and extracts the claims _but does not_
verify its signature. AppAuth only supports the OpenID Code flow, meaning ID Tokens
received by AppAuth are sent from the token endpoint on a TLS protected channel,
offering some assurances as to the origin of the token. You may wish to additionally
verify the ID Token signature using a JWT signature verification library of your
choosing.
@see http://openid.net/specs/openid-connect-core-1_0.html#IDToken
@see https://tools.ietf.org/html/rfc7519
@see https://jwt.io/
*/
@interface OIDIDToken : NSObject
/*! @internal
@brief Unavailable. Please use @c initWithAuthorizationResponse:.
*/
- (instancetype)init NS_UNAVAILABLE;
/*! @brief Parses the given ID Token string.
@param idToken The ID Token spring.
*/
- (nullable instancetype)initWithIDTokenString:(NSString *)idToken;
/*! @brief The header JWT values.
*/
@property(nonatomic, readonly) NSDictionary *header;
/*! @brief All ID Token claims.
*/
@property(nonatomic, readonly) NSDictionary *claims;
/*! @brief Issuer Identifier for the Issuer of the response.
@remarks iss
@see http://openid.net/specs/openid-connect-core-1_0.html#IDToken
*/
@property(nonatomic, readonly) NSURL *issuer;
/*! @brief Subject Identifier.
@remarks sub
@see http://openid.net/specs/openid-connect-core-1_0.html#IDToken
*/
@property(nonatomic, readonly) NSString *subject;
/*! @brief Audience(s) that this ID Token is intended for.
@remarks aud
@see http://openid.net/specs/openid-connect-core-1_0.html#IDToken
*/
@property(nonatomic, readonly) NSArray *audience;
/*! @brief Expiration time on or after which the ID Token MUST NOT be accepted for processing.
@remarks exp
@see http://openid.net/specs/openid-connect-core-1_0.html#IDToken
*/
@property(nonatomic, readonly) NSDate *expiresAt;
/*! @brief Time at which the JWT was issued.
@remarks iat
@see http://openid.net/specs/openid-connect-core-1_0.html#IDToken
*/
@property(nonatomic, readonly) NSDate *issuedAt;
/*! @brief String value used to associate a Client session with an ID Token, and to mitigate replay
attacks.
@remarks nonce
@see http://openid.net/specs/openid-connect-core-1_0.html#IDToken
*/
@property(nonatomic, readonly, nullable) NSString *nonce;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDIDToken.m
@brief AppAuth iOS SDK
@copyright
Copyright 2017 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDIDToken.h"
/*! Field keys associated with an ID Token. */
static NSString *const kIssKey = @"iss";
static NSString *const kSubKey = @"sub";
static NSString *const kAudKey = @"aud";
static NSString *const kExpKey = @"exp";
static NSString *const kIatKey = @"iat";
static NSString *const kNonceKey = @"nonce";
#import "OIDFieldMapping.h"
@implementation OIDIDToken
- (instancetype)initWithIDTokenString:(NSString *)idToken {
self = [super init];
NSArray *sections = [idToken componentsSeparatedByString:@"."];
// The header and claims sections are required.
if (sections.count <= 1) {
return nil;
}
_header = [[self class] parseJWTSection:sections[0]];
_claims = [[self class] parseJWTSection:sections[1]];
if (!_header || !_claims) {
return nil;
}
[OIDFieldMapping remainingParametersWithMap:[[self class] fieldMap]
parameters:_claims
instance:self];
// Required fields.
if (!_issuer || !_audience || !_subject || !_expiresAt || !_issuedAt) {
return nil;
}
return self;
}
/*! @brief Returns a mapping of incoming parameters to instance variables.
@return A mapping of incoming parameters to instance variables.
*/
+ (NSDictionary<NSString *, OIDFieldMapping *> *)fieldMap {
static NSMutableDictionary<NSString *, OIDFieldMapping *> *fieldMap;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
fieldMap = [NSMutableDictionary dictionary];
fieldMap[kIssKey] =
[[OIDFieldMapping alloc] initWithName:@"_issuer"
type:[NSURL class]
conversion:[OIDFieldMapping URLConversion]];
fieldMap[kSubKey] =
[[OIDFieldMapping alloc] initWithName:@"_subject" type:[NSString class]];
fieldMap[kAudKey] =
[[OIDFieldMapping alloc] initWithName:@"_audience"
type:[NSArray class]
conversion:^id _Nullable(NSObject *_Nullable value) {
if ([value isKindOfClass:[NSArray class]]) {
return value;
}
if ([value isKindOfClass:[NSString class]]) {
return @[value];
}
return nil;
}];
fieldMap[kExpKey] =
[[OIDFieldMapping alloc] initWithName:@"_expiresAt"
type:[NSDate class]
conversion:^id _Nullable(NSObject *_Nullable value) {
if (![value isKindOfClass:[NSNumber class]]) {
return value;
}
NSNumber *valueAsNumber = (NSNumber *)value;
return [NSDate dateWithTimeIntervalSince1970:valueAsNumber.longLongValue];
}];
fieldMap[kIatKey] =
[[OIDFieldMapping alloc] initWithName:@"_issuedAt"
type:[NSDate class]
conversion:^id _Nullable(NSObject *_Nullable value) {
if (![value isKindOfClass:[NSNumber class]]) {
return value;
}
NSNumber *valueAsNumber = (NSNumber *)value;
return [NSDate dateWithTimeIntervalSince1970:valueAsNumber.longLongValue];
}];
fieldMap[kNonceKey] =
[[OIDFieldMapping alloc] initWithName:@"_nonce" type:[NSString class]];
});
return fieldMap;
}
+ (NSDictionary *)parseJWTSection:(NSString *)sectionString {
NSData *decodedData = [[self class] base64urlNoPaddingDecode:sectionString];
// Parses JSON.
NSError *error;
id object = [NSJSONSerialization JSONObjectWithData:decodedData options:0 error:&error];
if (error) {
NSLog(@"Error %@ parsing token payload %@", error, sectionString);
}
if ([object isKindOfClass:[NSDictionary class]]) {
return (NSDictionary *)object;
}
return nil;
}
+ (NSData *)base64urlNoPaddingDecode:(NSString *)base64urlNoPaddingString {
NSMutableString *body = [base64urlNoPaddingString mutableCopy];
// Converts base64url to base64.
NSRange range = NSMakeRange(0, base64urlNoPaddingString.length);
[body replaceOccurrencesOfString:@"-" withString:@"+" options:NSLiteralSearch range:range];
[body replaceOccurrencesOfString:@"_" withString:@"/" options:NSLiteralSearch range:range];
// Converts base64 no padding to base64 with padding
while (body.length % 4 != 0) {
[body appendString:@"="];
}
// Decodes base64 string.
NSData *decodedData = [[NSData alloc] initWithBase64EncodedString:body options:0];
return decodedData;
}
@end
/*! @file OIDRegistrationRequest.h
@brief AppAuth iOS SDK
@copyright
Copyright 2016 The AppAuth for iOS Authors. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
@class OIDAuthorizationResponse;
@class OIDServiceConfiguration;
NS_ASSUME_NONNULL_BEGIN
/*! @brief Represents a registration request.
@see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationRequest
*/
@interface OIDRegistrationRequest : NSObject <NSCopying, NSSecureCoding>
/*! @brief The service's configuration.
@remarks This configuration specifies how to connect to a particular OAuth provider.
Configurations may be created manually, or via an OpenID Connect Discovery Document.
*/
@property(nonatomic, readonly) OIDServiceConfiguration *configuration;
/*! @brief The initial access token to access the Client Registration Endpoint
(if required by the OpenID Provider).
@remarks OAuth 2.0 Access Token optionally issued by an Authorization Server granting
access to its Client Registration Endpoint. This token (if required) is
provisioned out of band.
@see Section 3 of OpenID Connect Dynamic Client Registration 1.0
https://openid.net/specs/openid-connect-registration-1_0.html#ClientRegistration
*/
@property(nonatomic, readonly) NSString *initialAccessToken;
/*! @brief The application type to register, will always be 'native'.
@remarks application_type
@see https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata
*/
@property(nonatomic, readonly) NSString *applicationType;
/*! @brief The client's redirect URI's.
@remarks redirect_uris
@see https://tools.ietf.org/html/rfc6749#section-3.1.2
*/
@property(nonatomic, readonly) NSArray<NSURL *> *redirectURIs;
/*! @brief The response types to register for usage by this client.
@remarks response_types
@see http://openid.net/specs/openid-connect-core-1_0.html#Authentication
*/
@property(nonatomic, readonly, nullable) NSArray<NSString *> *responseTypes;
/*! @brief The grant types to register for usage by this client.
@remarks grant_types
@see https://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata
*/
@property(nonatomic, readonly, nullable) NSArray<NSString *> *grantTypes;
/*! @brief The subject type to to request.
@remarks subject_type
@see http://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes
*/
@property(nonatomic, readonly, nullable) NSString *subjectType;
/*! @brief The client authentication method to use at the token endpoint.
@remarks token_endpoint_auth_method
@see http://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication
*/
@property(nonatomic, readonly, nullable) NSString *tokenEndpointAuthenticationMethod;
/*! @brief The client's additional token request parameters.
*/
@property(nonatomic, readonly, nullable) NSDictionary<NSString *, NSString *> *additionalParameters;
/*! @internal
@brief Unavailable. Please use initWithConfiguration
*/
- (instancetype)init NS_UNAVAILABLE;
/*! @brief Create a Client Registration Request to an OpenID Provider that supports open Dynamic
Registration.
@param configuration The service's configuration.
@param redirectURIs The redirect URIs to register for the client.
@param responseTypes The response types to register for the client.
@param grantTypes The grant types to register for the client.
@param subjectType The subject type to register for the client.
@param tokenEndpointAuthMethod The token endpoint authentication method to register for the
client.
@param additionalParameters The client's additional registration request parameters.
*/
- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration
redirectURIs:(NSArray<NSURL *> *)redirectURIs
responseTypes:(nullable NSArray<NSString *> *)responseTypes
grantTypes:(nullable NSArray<NSString *> *)grantTypes
subjectType:(nullable NSString *)subjectType
tokenEndpointAuthMethod:(nullable NSString *)tokenEndpointAuthMethod
additionalParameters:(nullable NSDictionary<NSString *, NSString *> *)additionalParameters;
/*! @brief Designated initializer.
@param configuration The service's configuration.
@param redirectURIs The redirect URIs to register for the client.
@param responseTypes The response types to register for the client.
@param grantTypes The grant types to register for the client.
@param subjectType The subject type to register for the client.
@param tokenEndpointAuthMethod The token endpoint authentication method to register for the
client.
@param initialAccessToken The initial access token to access the Client Registration Endpoint
(if required by the OpenID Provider).
@param additionalParameters The client's additional registration request parameters.
@see https://openid.net/specs/openid-connect-registration-1_0.html#ClientRegistration
*/
- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration
redirectURIs:(NSArray<NSURL *> *)redirectURIs
responseTypes:(nullable NSArray<NSString *> *)responseTypes
grantTypes:(nullable NSArray<NSString *> *)grantTypes
subjectType:(nullable NSString *)subjectType
tokenEndpointAuthMethod:(nullable NSString *)tokenEndpointAuthMethod
initialAccessToken:(nullable NSString *)initialAccessToken
additionalParameters:(nullable NSDictionary<NSString *, NSString *> *)additionalParameters
NS_DESIGNATED_INITIALIZER;
/*! @brief Constructs an @c NSURLRequest representing the registration request.
@return An @c NSURLRequest representing the registration request.
*/
- (NSURLRequest *)URLRequest;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDRegistrationResponse.h
@brief AppAuth iOS SDK
@copyright
Copyright 2016 The AppAuth for iOS Authors. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
@class OIDRegistrationRequest;
NS_ASSUME_NONNULL_BEGIN
/*! @brief Parameter name for the client id.
*/
extern NSString *const OIDClientIDParam;
/*! @brief Parameter name for the client id issuance timestamp.
*/
extern NSString *const OIDClientIDIssuedAtParam;
/*! @brief Parameter name for the client secret.
*/
extern NSString *const OIDClientSecretParam;
/*! @brief Parameter name for the client secret expiration time.
*/
extern NSString *const OIDClientSecretExpirestAtParam;
/*! @brief Parameter name for the registration access token.
*/
extern NSString *const OIDRegistrationAccessTokenParam;
/*! @brief Parameter name for the client configuration URI.
*/
extern NSString *const OIDRegistrationClientURIParam;
/*! @brief Represents a registration response.
@see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationResponse
*/
@interface OIDRegistrationResponse : NSObject <NSCopying, NSSecureCoding>
/*! @brief The request which was serviced.
*/
@property(nonatomic, readonly) OIDRegistrationRequest *request;
/*! @brief The registered client identifier.
@remarks client_id
@see https://tools.ietf.org/html/rfc6749#section-4
@see https://tools.ietf.org/html/rfc6749#section-4.1.1
*/
@property(nonatomic, readonly) NSString *clientID;
/*! @brief Timestamp of when the client identifier was issued, if provided.
@remarks client_id_issued_at
@see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationResponse
*/
@property(nonatomic, readonly, nullable) NSDate *clientIDIssuedAt;
/*! @brief TThe client secret, which is part of the client credentials, if provided.
@remarks client_secret
@see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationResponse
*/
@property(nonatomic, readonly, nullable) NSString *clientSecret;
/*! @brief Timestamp of when the client credentials expires, if provided.
@remarks client_secret_expires_at
@see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationResponse
*/
@property(nonatomic, readonly, nullable) NSDate *clientSecretExpiresAt;
/*! @brief Client registration access token that can be used for subsequent operations upon the
client registration.
@remarks registration_access_token
@see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationResponse
*/
@property(nonatomic, readonly, nullable) NSString *registrationAccessToken;
/*! @brief Location of the client configuration endpoint, if provided.
@remarks registration_client_uri
@see https://openid.net/specs/openid-connect-registration-1_0.html#RegistrationResponse
*/
@property(nonatomic, readonly, nullable) NSURL *registrationClientURI;
/*! @brief Client authentication method to use at the token endpoint, if provided.
@remarks token_endpoint_auth_method
@see http://openid.net/specs/openid-connect-core-1_0.html#ClientAuthentication
*/
@property(nonatomic, readonly, nullable) NSString *tokenEndpointAuthenticationMethod;
/*! @brief Additional parameters returned from the token server.
*/
@property(nonatomic, readonly, nullable) NSDictionary<NSString *, NSObject <NSCopying> *>
*additionalParameters;
/*! @internal
@brief Unavailable. Please use initWithRequest
*/
- (instancetype)init NS_UNAVAILABLE;
/*! @brief Designated initializer.
@param request The serviced request.
@param parameters The decoded parameters returned from the Authorization Server.
@remarks Known parameters are extracted from the @c parameters parameter and the normative
properties are populated. Non-normative parameters are placed in the
@c #additionalParameters dictionary.
*/
- (instancetype)initWithRequest:(OIDRegistrationRequest *)request
parameters:(NSDictionary<NSString *, NSObject <NSCopying> *> *)parameters
NS_DESIGNATED_INITIALIZER;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDRegistrationResponse.m
@brief AppAuth iOS SDK
@copyright
Copyright 2016 The AppAuth for iOS Authors. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDRegistrationResponse.h"
#import "OIDClientMetadataParameters.h"
#import "OIDDefines.h"
#import "OIDFieldMapping.h"
#import "OIDRegistrationRequest.h"
#import "OIDTokenUtilities.h"
NSString *const OIDClientIDParam = @"client_id";
NSString *const OIDClientIDIssuedAtParam = @"client_id_issued_at";
NSString *const OIDClientSecretParam = @"client_secret";
NSString *const OIDClientSecretExpirestAtParam = @"client_secret_expires_at";
NSString *const OIDRegistrationAccessTokenParam = @"registration_access_token";
NSString *const OIDRegistrationClientURIParam = @"registration_client_uri";
/*! @brief Key used to encode the @c request property for @c NSSecureCoding
*/
static NSString *const kRequestKey = @"request";
/*! @brief Key used to encode the @c additionalParameters property for @c NSSecureCoding
*/
static NSString *const kAdditionalParametersKey = @"additionalParameters";
@implementation OIDRegistrationResponse
/*! @brief Returns a mapping of incoming parameters to instance variables.
@return A mapping of incoming parameters to instance variables.
*/
+ (NSDictionary<NSString *, OIDFieldMapping *> *)fieldMap {
static NSMutableDictionary<NSString *, OIDFieldMapping *> *fieldMap;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
fieldMap = [NSMutableDictionary dictionary];
fieldMap[OIDClientIDParam] = [[OIDFieldMapping alloc] initWithName:@"_clientID"
type:[NSString class]];
fieldMap[OIDClientIDIssuedAtParam] =
[[OIDFieldMapping alloc] initWithName:@"_clientIDIssuedAt"
type:[NSDate class]
conversion:[OIDFieldMapping dateEpochConversion]];
fieldMap[OIDClientSecretParam] =
[[OIDFieldMapping alloc] initWithName:@"_clientSecret"
type:[NSString class]];
fieldMap[OIDClientSecretExpirestAtParam] =
[[OIDFieldMapping alloc] initWithName:@"_clientSecretExpiresAt"
type:[NSDate class]
conversion:[OIDFieldMapping dateEpochConversion]];
fieldMap[OIDRegistrationAccessTokenParam] =
[[OIDFieldMapping alloc] initWithName:@"_registrationAccessToken"
type:[NSString class]];
fieldMap[OIDRegistrationClientURIParam] =
[[OIDFieldMapping alloc] initWithName:@"_registrationClientURI"
type:[NSURL class]
conversion:[OIDFieldMapping URLConversion]];
fieldMap[OIDTokenEndpointAuthenticationMethodParam] =
[[OIDFieldMapping alloc] initWithName:@"_tokenEndpointAuthenticationMethod"
type:[NSString class]];
});
return fieldMap;
}
#pragma mark - Initializers
- (nonnull instancetype)init
OID_UNAVAILABLE_USE_INITIALIZER(@selector(initWithRequest:parameters:))
- (instancetype)initWithRequest:(OIDRegistrationRequest *)request
parameters:(NSDictionary<NSString *, NSObject <NSCopying> *> *)parameters {
self = [super init];
if (self) {
_request = [request copy];
NSDictionary<NSString *, NSObject <NSCopying> *> *additionalParameters =
[OIDFieldMapping remainingParametersWithMap:[[self class] fieldMap]
parameters:parameters
instance:self];
_additionalParameters = additionalParameters;
if ((_clientSecret && !_clientSecretExpiresAt)
|| (!!_registrationClientURI != !!_registrationAccessToken)) {
// If client_secret is issued, client_secret_expires_at is REQUIRED,
// and the response MUST contain "[...] both a Client Configuration Endpoint
// and a Registration Access Token or neither of them"
return nil;
}
}
return self;
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(nullable NSZone *)zone {
// The documentation for NSCopying specifically advises us to return a reference to the original
// instance in the case where instances are immutable (as ours is):
// "Implement NSCopying by retaining the original instead of creating a new copy when the class
// and its contents are immutable."
return self;
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {
OIDRegistrationRequest *request = [aDecoder decodeObjectOfClass:[OIDRegistrationRequest class]
forKey:kRequestKey];
self = [self initWithRequest:request
parameters:@{}];
if (self) {
[OIDFieldMapping decodeWithCoder:aDecoder
map:[[self class] fieldMap]
instance:self];
_additionalParameters = [aDecoder decodeObjectOfClasses:[OIDFieldMapping JSONTypes]
forKey:kAdditionalParametersKey];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[OIDFieldMapping encodeWithCoder:aCoder map:[[self class] fieldMap] instance:self];
[aCoder encodeObject:_request forKey:kRequestKey];
[aCoder encodeObject:_additionalParameters forKey:kAdditionalParametersKey];
}
#pragma mark - NSObject overrides
- (NSString *)description {
return [NSString stringWithFormat:@"<%@: %p, clientID: \"%@\", clientIDIssuedAt: %@, "
"clientSecret: %@, clientSecretExpiresAt: \"%@\", "
"registrationAccessToken: \"%@\", "
"registrationClientURI: \"%@\", "
"additionalParameters: %@, request: %@>",
NSStringFromClass([self class]),
(void *)self,
_clientID,
_clientIDIssuedAt,
[OIDTokenUtilities redact:_clientSecret],
_clientSecretExpiresAt,
[OIDTokenUtilities redact:_registrationAccessToken],
_registrationClientURI,
_additionalParameters,
_request];
}
@end
/*! @file OIDResponseTypes.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
/*! @brief A constant for the standard OAuth2 Response Type of 'code'.
*/
extern NSString *const OIDResponseTypeCode;
/*! @brief A constant for the standard OAuth2 Response Type of 'token'.
*/
extern NSString *const OIDResponseTypeToken;
/*! @brief A constant for the standard OAuth2 Response Type of 'id_token'.
*/
extern NSString *const OIDResponseTypeIDToken;
/*! @file OIDResponseTypes.m
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDResponseTypes.h"
NSString *const OIDResponseTypeCode = @"code";
NSString *const OIDResponseTypeToken = @"token";
NSString *const OIDResponseTypeIDToken = @"id_token";
/*! @file OIDScopeUtilities.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/*! @brief Provides convenience methods for dealing with scope strings.
*/
@interface OIDScopeUtilities : NSObject
/*! @internal
@brief Unavailable. This class should not be initialized.
*/
- (instancetype)init NS_UNAVAILABLE;
/*! @brief Converts an array of scope strings to a single scope string per the OAuth 2 spec.
@param scopes An array of scope strings.
@return A space-delimited string of scopes.
@see https://tools.ietf.org/html/rfc6749#section-3.3
*/
+ (NSString *)scopesWithArray:(NSArray<NSString *> *)scopes;
/*! @brief Converts an OAuth 2 spec-compliant scope string to an array of scopes.
@param scopes An OAuth 2 spec-compliant scope string.
@return An array of scope strings.
@see https://tools.ietf.org/html/rfc6749#section-3.3
*/
+ (NSArray<NSString *> *)scopesArrayWithString:(NSString *)scopes;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDScopeUtilities.m
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDScopeUtilities.h"
@implementation OIDScopeUtilities
/*! @brief A character set with the characters NOT allowed in a scope name.
@see https://tools.ietf.org/html/rfc6749#section-3.3
*/
+ (NSCharacterSet *)disallowedScopeCharacters {
static NSCharacterSet *disallowedCharacters;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSMutableCharacterSet *allowedCharacters;
allowedCharacters =
[NSMutableCharacterSet characterSetWithRange:NSMakeRange(0x23, 0x5B - 0x23 + 1)];
[allowedCharacters addCharactersInRange:NSMakeRange(0x5D, 0x7E - 0x5D + 1)];
[allowedCharacters addCharactersInString:@"\x21"];
disallowedCharacters = [allowedCharacters invertedSet];
});
return disallowedCharacters;
}
+ (NSString *)scopesWithArray:(NSArray<NSString *> *)scopes {
#if !defined(NS_BLOCK_ASSERTIONS)
NSCharacterSet *disallowedCharacters = [self disallowedScopeCharacters];
for (NSString *scope in scopes) {
NSAssert(scope.length, @"Found illegal empty scope string.");
NSAssert([scope rangeOfCharacterFromSet:disallowedCharacters].location == NSNotFound,
@"Found illegal character in scope string.");
}
#endif // !defined(NS_BLOCK_ASSERTIONS)
NSString *scopeString = [scopes componentsJoinedByString:@" "];
return scopeString;
}
+ (NSArray<NSString *> *)scopesArrayWithString:(NSString *)scopes {
return [scopes componentsSeparatedByString:@" "];
}
@end
/*! @file OIDScopes.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
/*! @brief Scope that indicates this request is an OpenID Connect request.
@see http://openid.net/specs/openid-connect-core-1_0.html#AuthRequestValidation
*/
extern NSString *const OIDScopeOpenID;
/*! @brief This scope value requests access to the End-User's default profile Claims, which are:
name, family_name, given_name, middle_name, nickname, preferred_username, profile, picture,
website, gender, birthdate, zoneinfo, locale, and updated_at.
@see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims
*/
extern NSString *const OIDScopeProfile;
/*! @brief This scope value requests access to the email and email_verified Claims.
@see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims
*/
extern NSString *const OIDScopeEmail;
/*! @brief This scope value requests access to the address Claim.
@see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims
*/
extern NSString *const OIDScopeAddress;
/*! @brief This scope value requests access to the phone_number and phone_number_verified Claims.
@see http://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims
*/
extern NSString *const OIDScopePhone;
/*! @file OIDScopes.m
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDScopes.h"
NSString *const OIDScopeOpenID = @"openid";
NSString *const OIDScopeProfile = @"profile";
NSString *const OIDScopeEmail = @"email";
NSString *const OIDScopeAddress = @"address";
NSString *const OIDScopePhone = @"phone";
/*! @file OIDServiceConfiguration.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
@class OIDServiceConfiguration;
@class OIDServiceDiscovery;
NS_ASSUME_NONNULL_BEGIN
/*! @brief The type of block called when a @c OIDServiceConfiguration has been created
by loading a @c OIDServiceDiscovery from an @c NSURL.
*/
typedef void (^OIDServiceConfigurationCreated)
(OIDServiceConfiguration *_Nullable serviceConfiguration,
NSError *_Nullable error);
/*! @brief Represents the information needed to construct a @c OIDAuthorizationService.
*/
@interface OIDServiceConfiguration : NSObject <NSCopying, NSSecureCoding>
/*! @brief The authorization endpoint URI.
*/
@property(nonatomic, readonly) NSURL *authorizationEndpoint;
/*! @brief The token exchange and refresh endpoint URI.
*/
@property(nonatomic, readonly) NSURL *tokenEndpoint;
/*! @brief The OpenID Connect issuer.
*/
@property(nonatomic, readonly, nullable) NSURL *issuer;
/*! @brief The dynamic client registration endpoint URI.
*/
@property(nonatomic, readonly, nullable) NSURL *registrationEndpoint;
/*! @brief The end session logout endpoint URI.
*/
@property(nonatomic, readonly, nullable) NSURL *endSessionEndpoint;
/*! @brief The discovery document.
*/
@property(nonatomic, readonly, nullable) OIDServiceDiscovery *discoveryDocument;
/*! @internal
@brief Unavailable. Please use @c initWithAuthorizationEndpoint:tokenEndpoint: or
@c initWithDiscoveryDocument:.
*/
- (instancetype)init NS_UNAVAILABLE;
/*! @param authorizationEndpoint The authorization endpoint URI.
@param tokenEndpoint The token exchange and refresh endpoint URI.
*/
- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint
tokenEndpoint:(NSURL *)tokenEndpoint;
/*! @param authorizationEndpoint The authorization endpoint URI.
@param tokenEndpoint The token exchange and refresh endpoint URI.
@param registrationEndpoint The dynamic client registration endpoint URI.
*/
- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint
tokenEndpoint:(NSURL *)tokenEndpoint
registrationEndpoint:(nullable NSURL *)registrationEndpoint;
/*! @param authorizationEndpoint The authorization endpoint URI.
@param tokenEndpoint The token exchange and refresh endpoint URI.
@param issuer The OpenID Connect issuer.
*/
- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint
tokenEndpoint:(NSURL *)tokenEndpoint
issuer:(nullable NSURL *)issuer;
/*! @param authorizationEndpoint The authorization endpoint URI.
@param tokenEndpoint The token exchange and refresh endpoint URI.
@param issuer The OpenID Connect issuer.
@param registrationEndpoint The dynamic client registration endpoint URI.
*/
- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint
tokenEndpoint:(NSURL *)tokenEndpoint
issuer:(nullable NSURL *)issuer
registrationEndpoint:(nullable NSURL *)registrationEndpoint;
/*! @param authorizationEndpoint The authorization endpoint URI.
@param tokenEndpoint The token exchange and refresh endpoint URI.
@param issuer The OpenID Connect issuer.
@param registrationEndpoint The dynamic client registration endpoint URI.
@param endSessionEndpoint The end session endpoint (logout) URI.
*/
- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint
tokenEndpoint:(NSURL *)tokenEndpoint
issuer:(nullable NSURL *)issuer
registrationEndpoint:(nullable NSURL *)registrationEndpoint
endSessionEndpoint:(nullable NSURL *)endSessionEndpoint;
/*! @param discoveryDocument The discovery document from which to extract the required OAuth
configuration.
*/
- (instancetype)initWithDiscoveryDocument:(OIDServiceDiscovery *)discoveryDocument;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDServiceConfiguration.m
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import "OIDServiceConfiguration.h"
#import "OIDDefines.h"
#import "OIDErrorUtilities.h"
#import "OIDServiceDiscovery.h"
/*! @brief The key for the @c authorizationEndpoint property.
*/
static NSString *const kAuthorizationEndpointKey = @"authorizationEndpoint";
/*! @brief The key for the @c tokenEndpoint property.
*/
static NSString *const kTokenEndpointKey = @"tokenEndpoint";
/*! @brief The key for the @c issuer property.
*/
static NSString *const kIssuerKey = @"issuer";
/*! @brief The key for the @c registrationEndpoint property.
*/
static NSString *const kRegistrationEndpointKey = @"registrationEndpoint";
/*! @brief The key for the @c endSessionEndpoint property.
*/
static NSString *const kEndSessionEndpointKey = @"endSessionEndpoint";
/*! @brief The key for the @c discoveryDocument property.
*/
static NSString *const kDiscoveryDocumentKey = @"discoveryDocument";
NS_ASSUME_NONNULL_BEGIN
@interface OIDServiceConfiguration ()
- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint
tokenEndpoint:(NSURL *)tokenEndpoint
issuer:(nullable NSURL *)issuer
registrationEndpoint:(nullable NSURL *)registrationEndpoint
endSessionEndpoint:(nullable NSURL *)endSessionEndpoint
discoveryDocument:(nullable OIDServiceDiscovery *)discoveryDocument
NS_DESIGNATED_INITIALIZER;
@end
@implementation OIDServiceConfiguration
- (instancetype)init
OID_UNAVAILABLE_USE_INITIALIZER(@selector(
initWithAuthorizationEndpoint:
tokenEndpoint:)
)
- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint
tokenEndpoint:(NSURL *)tokenEndpoint
issuer:(nullable NSURL *)issuer
registrationEndpoint:(nullable NSURL *)registrationEndpoint
endSessionEndpoint:(nullable OIDServiceDiscovery *)endSessionEndpoint
discoveryDocument:(nullable OIDServiceDiscovery *)discoveryDocument {
self = [super init];
if (self) {
_authorizationEndpoint = [authorizationEndpoint copy];
_tokenEndpoint = [tokenEndpoint copy];
_issuer = [issuer copy];
_registrationEndpoint = [registrationEndpoint copy];
_endSessionEndpoint = [endSessionEndpoint copy];
_discoveryDocument = [discoveryDocument copy];
}
return self;
}
- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint
tokenEndpoint:(NSURL *)tokenEndpoint {
return [self initWithAuthorizationEndpoint:authorizationEndpoint
tokenEndpoint:tokenEndpoint
issuer:nil
registrationEndpoint:nil
endSessionEndpoint:nil
discoveryDocument:nil];
}
- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint
tokenEndpoint:(NSURL *)tokenEndpoint
registrationEndpoint:(nullable NSURL *)registrationEndpoint {
return [self initWithAuthorizationEndpoint:authorizationEndpoint
tokenEndpoint:tokenEndpoint
issuer:nil
registrationEndpoint:registrationEndpoint
endSessionEndpoint:nil
discoveryDocument:nil];
}
- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint
tokenEndpoint:(NSURL *)tokenEndpoint
issuer:(nullable NSURL *)issuer {
return [self initWithAuthorizationEndpoint:authorizationEndpoint
tokenEndpoint:tokenEndpoint
issuer:issuer
registrationEndpoint:nil
endSessionEndpoint:nil
discoveryDocument:nil];
}
- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint
tokenEndpoint:(NSURL *)tokenEndpoint
issuer:(nullable NSURL *)issuer
registrationEndpoint:(nullable NSURL *)registrationEndpoint {
return [self initWithAuthorizationEndpoint:authorizationEndpoint
tokenEndpoint:tokenEndpoint
issuer:issuer
registrationEndpoint:registrationEndpoint
endSessionEndpoint:nil
discoveryDocument:nil];
}
- (instancetype)initWithAuthorizationEndpoint:(NSURL *)authorizationEndpoint
tokenEndpoint:(NSURL *)tokenEndpoint
issuer:(nullable NSURL *)issuer
registrationEndpoint:(nullable NSURL *)registrationEndpoint
endSessionEndpoint:(nullable NSURL *)endSessionEndpoint {
return [self initWithAuthorizationEndpoint:authorizationEndpoint
tokenEndpoint:tokenEndpoint
issuer:issuer
registrationEndpoint:registrationEndpoint
endSessionEndpoint:endSessionEndpoint
discoveryDocument:nil];
}
- (instancetype)initWithDiscoveryDocument:(OIDServiceDiscovery *) discoveryDocument {
return [self initWithAuthorizationEndpoint:discoveryDocument.authorizationEndpoint
tokenEndpoint:discoveryDocument.tokenEndpoint
issuer:discoveryDocument.issuer
registrationEndpoint:discoveryDocument.registrationEndpoint
endSessionEndpoint:discoveryDocument.endSessionEndpoint
discoveryDocument:discoveryDocument];
}
#pragma mark - NSCopying
- (instancetype)copyWithZone:(nullable NSZone *)zone {
// The documentation for NSCopying specifically advises us to return a reference to the original
// instance in the case where instances are immutable (as ours is):
// "Implement NSCopying by retaining the original instead of creating a new copy when the class
// and its contents are immutable."
return self;
}
#pragma mark - NSSecureCoding
+ (BOOL)supportsSecureCoding {
return YES;
}
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {
NSURL *authorizationEndpoint = [aDecoder decodeObjectOfClass:[NSURL class]
forKey:kAuthorizationEndpointKey];
NSURL *tokenEndpoint = [aDecoder decodeObjectOfClass:[NSURL class]
forKey:kTokenEndpointKey];
NSURL *issuer = [aDecoder decodeObjectOfClass:[NSURL class]
forKey:kIssuerKey];
NSURL *registrationEndpoint = [aDecoder decodeObjectOfClass:[NSURL class]
forKey:kRegistrationEndpointKey];
NSURL *endSessionEndpoint = [aDecoder decodeObjectOfClass:[NSURL class]
forKey:kEndSessionEndpointKey];
// We don't accept nil authorizationEndpoints or tokenEndpoints.
if (!authorizationEndpoint || !tokenEndpoint) {
return nil;
}
OIDServiceDiscovery *discoveryDocument = [aDecoder decodeObjectOfClass:[OIDServiceDiscovery class]
forKey:kDiscoveryDocumentKey];
return [self initWithAuthorizationEndpoint:authorizationEndpoint
tokenEndpoint:tokenEndpoint
issuer:issuer
registrationEndpoint:registrationEndpoint
endSessionEndpoint:endSessionEndpoint
discoveryDocument:discoveryDocument];
}
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:_authorizationEndpoint forKey:kAuthorizationEndpointKey];
[aCoder encodeObject:_tokenEndpoint forKey:kTokenEndpointKey];
[aCoder encodeObject:_issuer forKey:kIssuerKey];
[aCoder encodeObject:_registrationEndpoint forKey:kRegistrationEndpointKey];
[aCoder encodeObject:_discoveryDocument forKey:kDiscoveryDocumentKey];
[aCoder encodeObject:_endSessionEndpoint forKey:kEndSessionEndpointKey];
}
#pragma mark - description
- (NSString *)description {
return [NSString stringWithFormat:
@"OIDServiceConfiguration authorizationEndpoint: %@, tokenEndpoint: %@, "
"registrationEndpoint: %@, endSessionEndpoint: %@, discoveryDocument: [%@]",
_authorizationEndpoint,
_tokenEndpoint,
_registrationEndpoint,
_endSessionEndpoint,
_discoveryDocument];
}
@end
NS_ASSUME_NONNULL_END
/*! @file OIDTokenRequest.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
// This file only declares string constants useful for constructing a @c OIDTokenRequest, so it is
// imported here for convenience.
#import "OIDGrantTypes.h"
@class OIDAuthorizationResponse;
@class OIDServiceConfiguration;
NS_ASSUME_NONNULL_BEGIN
/*! @brief Represents a token request.
@see https://tools.ietf.org/html/rfc6749#section-3.2
@see https://tools.ietf.org/html/rfc6749#section-4.1.3
*/
@interface OIDTokenRequest : NSObject <NSCopying, NSSecureCoding>
/*! @brief The service's configuration.
@remarks This configuration specifies how to connect to a particular OAuth provider.
Configurations may be created manually, or via an OpenID Connect Discovery Document.
*/
@property(nonatomic, readonly) OIDServiceConfiguration *configuration;
/*! @brief The type of token being sent to the token endpoint, i.e. "authorization_code" for the
authorization code exchange, or "refresh_token" for an access token refresh request.
@remarks grant_type
@see https://tools.ietf.org/html/rfc6749#section-4.1.3
@see https://www.google.com/url?sa=D&q=https%3A%2F%2Ftools.ietf.org%2Fhtml%2Frfc6749%23section-6
*/
@property(nonatomic, readonly) NSString *grantType;
/*! @brief The authorization code received from the authorization server.
@remarks code
@see https://tools.ietf.org/html/rfc6749#section-4.1.3
*/
@property(nonatomic, readonly, nullable) NSString *authorizationCode;
/*! @brief The client's redirect URI.
@remarks redirect_uri
@see https://tools.ietf.org/html/rfc6749#section-4.1.3
*/
@property(nonatomic, readonly, nullable) NSURL *redirectURL;
/*! @brief The client identifier.
@remarks client_id
@see https://tools.ietf.org/html/rfc6749#section-4.1.3
*/
@property(nonatomic, readonly) NSString *clientID;
/*! @brief The client secret.
@remarks client_secret
@see https://tools.ietf.org/html/rfc6749#section-2.3.1
*/
@property(nonatomic, readonly, nullable) NSString *clientSecret;
/*! @brief The value of the scope parameter is expressed as a list of space-delimited,
case-sensitive strings.
@remarks scope
@see https://tools.ietf.org/html/rfc6749#section-3.3
*/
@property(nonatomic, readonly, nullable) NSString *scope;
/*! @brief The refresh token, which can be used to obtain new access tokens using the same
authorization grant.
@remarks refresh_token
@see https://tools.ietf.org/html/rfc6749#section-5.1
*/
@property(nonatomic, readonly, nullable) NSString *refreshToken;
/*! @brief The PKCE code verifier used to redeem the authorization code.
@remarks code_verifier
@see https://tools.ietf.org/html/rfc7636#section-4.3
*/
@property(nonatomic, readonly, nullable) NSString *codeVerifier;
/*! @brief The client's additional token request parameters.
*/
@property(nonatomic, readonly, nullable) NSDictionary<NSString *, NSString *> *additionalParameters;
/*! @internal
@brief Unavailable. Please use
initWithConfiguration:grantType:code:redirectURL:clientID:additionalParameters:.
*/
- (instancetype)init NS_UNAVAILABLE;
/*! @param configuration The service's configuration.
@param grantType the type of token being sent to the token endpoint, i.e. "authorization_code"
for the authorization code exchange, or "refresh_token" for an access token refresh request.
@see OIDGrantTypes.h
@param code The authorization code received from the authorization server.
@param redirectURL The client's redirect URI.
@param clientID The client identifier.
@param clientSecret The client secret.
@param scopes An array of scopes to combine into a single scope string per the OAuth2 spec.
@param refreshToken The refresh token.
@param codeVerifier The PKCE code verifier.
@param additionalParameters The client's additional token request parameters.
*/
- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration
grantType:(NSString *)grantType
authorizationCode:(nullable NSString *)code
redirectURL:(nullable NSURL *)redirectURL
clientID:(NSString *)clientID
clientSecret:(nullable NSString *)clientSecret
scopes:(nullable NSArray<NSString *> *)scopes
refreshToken:(nullable NSString *)refreshToken
codeVerifier:(nullable NSString *)codeVerifier
additionalParameters:(nullable NSDictionary<NSString *, NSString *> *)additionalParameters;
/*! @brief Designated initializer.
@param configuration The service's configuration.
@param grantType the type of token being sent to the token endpoint, i.e. "authorization_code"
for the authorization code exchange, or "refresh_token" for an access token refresh request.
@see OIDGrantTypes.h
@param code The authorization code received from the authorization server.
@param redirectURL The client's redirect URI.
@param clientID The client identifier.
@param clientSecret The client secret.
@param scope The value of the scope parameter is expressed as a list of space-delimited,
case-sensitive strings.
@param refreshToken The refresh token.
@param codeVerifier The PKCE code verifier.
@param additionalParameters The client's additional token request parameters.
*/
- (instancetype)initWithConfiguration:(OIDServiceConfiguration *)configuration
grantType:(NSString *)grantType
authorizationCode:(nullable NSString *)code
redirectURL:(nullable NSURL *)redirectURL
clientID:(NSString *)clientID
clientSecret:(nullable NSString *)clientSecret
scope:(nullable NSString *)scope
refreshToken:(nullable NSString *)refreshToken
codeVerifier:(nullable NSString *)codeVerifier
additionalParameters:(nullable NSDictionary<NSString *, NSString *> *)additionalParameters
NS_DESIGNATED_INITIALIZER;
/*! @brief Constructs an @c NSURLRequest representing the token request.
@return An @c NSURLRequest representing the token request.
*/
- (NSURLRequest *)URLRequest;
@end
NS_ASSUME_NONNULL_END
/*! @file OIDTokenResponse.h
@brief AppAuth iOS SDK
@copyright
Copyright 2015 Google Inc. All Rights Reserved.
@copydetails
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#import <Foundation/Foundation.h>
@class OIDTokenRequest;
NS_ASSUME_NONNULL_BEGIN
/*! @brief Represents the response to an token request.
@see https://tools.ietf.org/html/rfc6749#section-3.2
@see https://tools.ietf.org/html/rfc6749#section-4.1.3
*/
@interface OIDTokenResponse : NSObject <NSCopying, NSSecureCoding>
/*! @brief The request which was serviced.
*/
@property(nonatomic, readonly) OIDTokenRequest *request;
/*! @brief The access token generated by the authorization server.
@remarks access_token
@see https://tools.ietf.org/html/rfc6749#section-4.1.4
@see https://tools.ietf.org/html/rfc6749#section-5.1
*/
@property(nonatomic, readonly, nullable) NSString *accessToken;
/*! @brief The approximate expiration date & time of the access token.
@remarks expires_in
@seealso OIDTokenResponse.accessToken
@see https://tools.ietf.org/html/rfc6749#section-4.1.4
@see https://tools.ietf.org/html/rfc6749#section-5.1
*/
@property(nonatomic, readonly, nullable) NSDate *accessTokenExpirationDate;
/*! @brief Typically "Bearer" when present. Otherwise, another token_type value that the Client has
negotiated with the Authorization Server.
@remarks token_type
@see https://tools.ietf.org/html/rfc6749#section-4.1.4
@see https://tools.ietf.org/html/rfc6749#section-5.1
*/
@property(nonatomic, readonly, nullable) NSString *tokenType;
/*! @brief ID Token value associated with the authenticated session. Always present for the
authorization code grant exchange when OpenID Connect is used, optional for responses to
access token refresh requests. Note that AppAuth does NOT verify the JWT signature. Users
of AppAuth are encouraged to verifying the JWT signature using the validation library of
their choosing.
@remarks id_token
@see http://openid.net/specs/openid-connect-core-1_0.html#TokenResponse
@see http://openid.net/specs/openid-connect-core-1_0.html#RefreshTokenResponse
@see http://openid.net/specs/openid-connect-core-1_0.html#IDToken
@see https://jwt.io
@discussion @c OIDIDToken can be used to parse the ID Token and extract the claims. As noted,
this class does not verify the JWT signature.
*/
@property(nonatomic, readonly, nullable) NSString *idToken;
/*! @brief The refresh token, which can be used to obtain new access tokens using the same
authorization grant
@remarks refresh_token
@see https://tools.ietf.org/html/rfc6749#section-5.1
*/
@property(nonatomic, readonly, nullable) NSString *refreshToken;
/*! @brief The scope of the access token. OPTIONAL, if identical to the scopes requested, otherwise,
REQUIRED.
@remarks scope
@see https://tools.ietf.org/html/rfc6749#section-5.1
*/
@property(nonatomic, readonly, nullable) NSString *scope;
/*! @brief Additional parameters returned from the token server.
*/
@property(nonatomic, readonly, nullable)
NSDictionary<NSString *, NSObject<NSCopying> *> *additionalParameters;
/*! @internal
@brief Unavailable. Please use initWithParameters:.
*/
- (instancetype)init NS_UNAVAILABLE;
/*! @brief Designated initializer.
@param request The serviced request.
@param parameters The decoded parameters returned from the Authorization Server.
@remarks Known parameters are extracted from the @c parameters parameter and the normative
properties are populated. Non-normative parameters are placed in the
@c #additionalParameters dictionary.
*/
- (instancetype)initWithRequest:(OIDTokenRequest *)request
parameters:(NSDictionary<NSString *, NSObject<NSCopying> *> *)parameters
NS_DESIGNATED_INITIALIZER;
@end
NS_ASSUME_NONNULL_END
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment