AWS Cognito User Pool + Facebook Login iOS - ios

I have started integrating AWS Cognito User Pools into my app and the signup + login works (I have followed this tutorial: https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-integrating-user-pools-ios.html)
Now I'm struggling to properly integrate a Facebook login. This is what I do:
After the user has successfully signed in with facebook (using the facebook SDK), I'm getting the token and calling this function:
func signInFacebook(){
let customProviderManager = CustomIdentityProvider(tokens: nil)
self.credentialsProvider = AWSCognitoCredentialsProvider(
regionType:CognitoIdentityUserPoolRegion,
identityPoolId: CognitoIdentityPoolId,
identityProviderManager: customProviderManager)
let configuration = AWSServiceConfiguration(region:CognitoIdentityUserPoolRegion, credentialsProvider: self.credentialsProvider!)
AWSServiceManager.default().defaultServiceConfiguration = configuration
}
My CustomIdentityProvider class looks like this:
class CustomIdentityProvider: NSObject, AWSIdentityProviderManager {
var tokens : NSDictionary?
init(tokens: NSDictionary?) {
self.tokens = tokens
}
func logins() -> AWSTask<NSDictionary> {
if let fbToken = AccessToken.current?.authenticationToken {
return AWSTask(result: [AWSIdentityProviderFacebook: fbToken])
} else if let googleToken = GIDSignIn.sharedInstance().currentUser.authentication.idToken {
return AWSTask(result: [AWSIdentityProviderGoogle: googleToken])
}
return AWSTask(error:NSError(domain: "Social login", code: -1 , userInfo: ["Social login" : "No current social access token"]))
}
}
After signInFacebook() is called, I also call
self.credentialsProvider?.credentials().continueOnSuccessWith { (task:AWSTask<AWSCredentials>) -> Any? in
print("credentials: \(task.result!)")
return nil
}
and it prints some data in the log which looks fine.
But for some reason it doesn't seem to link properly everything together.
When I'm calling my backend to fetch some data, I usually do it like this:
I call self.user?.getSession().continueOnSuccessWith (user is an instance of AWSCognitoIdentityUser) and inside the closure I build the request where I put the token in the header. But if there are no tokens, the SDK shows my login screen. And this is what happens all the time. I would expect the user object to be updated with the correct tokens after the social login with Facebook has succeeded. What am I doing wrong?

Related

Firebase Authentication Link Facebook to Google

After many tests I decided to create a new xCode project to better understand Firebase authentication with multiple providers.
I set up in Firebase -> SignIn Methods -> An account per email address
An account per email address
Prevents users from creating multiple
accounts using the same email address with different authentication
providers
At this point I have implemented, carefully following the Firebase guide, the login with Facebook and with Google .. Everything seems to work perfectly but I always find myself with the same error that I can't manage:
When my user creates a Firebase account via Google he is no longer able to log in if he decides to use Facebook.
Facebook returns its error when it completes its authentication flow with Firebase:
Firebase Error With Facebook Provider: An account already exists with the same email address but different sign-in credentials. Sign in using a provider associated with this email address.
Continuing to follow the documentation step by step I stopped here (firebase explains how to handle this error)
I have also implemented error handling but after calling Auth.auth().fetchSignInMethods Firebase says I should authenticate the user with the existing provider, at this point how do I get the credentials for authentication with the existing provider?
I wouldn't want to reopen the existing provider controller to get new credentials
Am I obliged to ask the user to log in with the existing provider and show another access controller again (in this case that of Google)?
How should I handle this situation?
override func viewDidLoad() {
super.viewDidLoad()
facebookSetup()
}
func facebookSetup() {
let loginButton = FBLoginButton(permissions: [ .publicProfile, .email ])
loginButton.center = view.center
loginButton.delegate = self
view.addSubview(loginButton)
}
//MARK: - FACEBOOK Delegate
func loginButton(_ loginButton: FBLoginButton, didCompleteWith result: LoginManagerLoginResult?, error: Error?) {
if let error = error {
print(error.localizedDescription)
return
}
let credential = FacebookAuthProvider.credential(withAccessToken: AccessToken.current!.tokenString)
Auth.auth().signIn(with: credential) { (authResult, error) in
if let error = error {
print("\n FIREBASE: ",error.localizedDescription)
// An account with the same email already exists.
if (error as NSError?)?.code == AuthErrorCode.accountExistsWithDifferentCredential.rawValue {
// Get pending credential and email of existing account.
let existingAcctEmail = (error as NSError).userInfo[AuthErrorUserInfoEmailKey] as! String
let pendingCred = (error as NSError).userInfo[AuthErrorUserInfoUpdatedCredentialKey] as! AuthCredential
// Lookup existing account identifier by the email.
Auth.auth().fetchSignInMethods(forEmail: existingAcctEmail) { providers, error in
if (providers?.contains(GoogleAuthProviderID))! {
// Sign in with existing account.
Auth.auth().signIn(with: "? ? ? ?") { user, error in
// Successfully signed in.
if user != nil {
// Link pending credential to account.
Auth.auth().currentUser?.link(with: pendingCred) { result, error in
// Link Facebook to Google Account
}
}
}
}
}
}
}
}

Passing LWA token to Cognito

I am working a an app which uses the Alexa Voice Service and maintains different users, so the users needs to login with Amazon (LWA). I have implemented it like it is written in the docs and it works flawlessly.
LWA docs: https://developer.amazon.com/de/docs/login-with-amazon/use-sdk-ios.html
AMZNAuthorizationManager.shared().authorize(request, withHandler: {(result : AMZNAuthorizeResult?, userDidCancel : Bool, error : Error?) -> () in
if error != nil {
// Handle errors from the SDK or authorization server.
}
else if userDidCancel {
// Handle errors caused when user cancels login.
}
else {
// Authentication was successful.
// Obtain the access token and user profile data.
self.accessToken = result!.token
self.user = result!.user!
}
})
Furthermore I need to retrieve information from DynamoDB, which uses Cognito for authentification. As stated in the docs, there should be a way pass the access token form LWA to Cognito, but I can't find the proper place to do it. They say LWA provides an AMZNAccessTokenDelegate, which it does not. The delegate method provides an API result which Cognito needs. The link in the Cognito docs below refers to the same exact link from the LWA docs I posted above.
Cognito docs: https://docs.aws.amazon.com/cognito/latest/developerguide/amazon.html
func requestDidSucceed(apiResult: APIResult!) {
if apiResult.api == API.AuthorizeUser {
AIMobileLib.getAccessTokenForScopes(["profile"], withOverrideParams: nil, delegate: self)
} else if apiResult.api == API.GetAccessToken {
credentialsProvider.logins = [AWSCognitoLoginProviderKey.LoginWithAmazon.rawValue: apiResult.result]
}
}
What am I missing?
[EDIT]
I crawled through the LWA sources today until I finally found the correct delegate method.
Use AIAuthenticationDelegate instead of AMZNAccessTokenDelegate
But that lets me sit in front of the next two problems:
I.
Value of type 'AWSCognitoCredentialsProvider' has no member 'logins'
Maybe I have to use the following?
.setValue([AWSCognitoLoginProviderKey.LoginWithAmazon.rawValue: apiResult.result], forKey: "logins")
II.
Use of unresolved identifier 'AWSCognitoLoginProviderKey'
What do I put here? Maybe the API key I got from LWA?
[EDIT2]
I wanted to try it out, but requestDidSucceed never gets called, even through I successfully logged in.
class CustomIdentityProvider: NSObject, AWSIdentityProviderManager {
func logins() -> AWSTask<NSDictionary> {
return AWSTask(result: loginTokens)
}
var loginTokens : NSDictionary
init(tokens: [String : String]) {
self.loginTokens = tokens as NSDictionary
}
}
in the Authorization code at this below in successsful
AMZNAuthorizationManager.shared().authorize(request) { (result, userDidCancel, error) in
if ((error) != nil) {
// Handle errors from the SDK or authorization server.
} else if (userDidCancel) {
// Handle errors caused when user cancels login.
} else {
let logins = [IdentityProvider.amazon.rawValue: result!.token]
let customProviderManager = CustomIdentityProvider(tokens: logins)
guard let apiGatewayEndpoint = AWSEndpoint(url: URL(string: "APIGATEWAYURL")) else {
fatalError("Error creating API Gateway endpoint url")
}
let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USWest2, identityPoolId: "IDENTITY_ID", identityProviderManager:customProviderManager)
let configuration = AWSServiceConfiguration(region: .USWest2, endpoint: apiGatewayEndpoint, credentialsProvider: credentialsProvider)
}

How do I get to AccessToken and IdToken following successful Amazon Cognito Login from iOS

I have been using the following sample to introduce cognito login to my iOS application:
https://github.com/awslabs/aws-sdk-ios-samples/tree/master/CognitoYourUserPools-Sample
This is working well and I am at the point where I have a AWSCognitoIdentityUserPool object which I can call the currentUser() method to access the user.
What I am struggling to find is how I extract both the AccessToken and the IdToken.
In the android equivalent, the onSuccess method of the AuthenticationHandler has a CognitoUserSession argument which in turn has getIdToken() and getAccessToken().
Frustratingly, I see them output as the AuthenticationResult in json format in the output window, but I just don't know how to access them programatically?
Figured it out now:
func getSession(){
self.user?.getSession().continueOnSuccessWith { (getSessionTask) -> AnyObject? in
DispatchQueue.main.async(execute: {
let getSessionResult = getSessionTask.result
self.idToken = getSessionResult?.idToken?.tokenString
self.accessToken = getSessionResult?.accessToken?.tokenString
})
return nil
}
}

Using DynamoDB With Cognito: Token is not from a supported provider of this identity pool

I am in the process of implementing registration and login for my iOS app, using this project as an example:
https://github.com/awslabs/aws-sdk-ios-samples/tree/75ada5b6283b7c04c1214b2e1e0a6394377e3f2b/CognitoYourUserPools-Sample/Objective-C/CognitoYourUserPoolsSample
Previously, my app was able to access DynamoDB resources by using a credentials provider set up in my AppDelegate's didFinishLaunchingWithOptions method. However, after changing my project to include logging in and function like the example, I see the error:
"__type":"NotAuthorizedException","message":"Token is not from a supported provider of this identity pool."
The code setting the credentialsProviderin AppDelegate currently looks like this:
let serviceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: nil)
let userPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId:APP_CLIENT_ID, clientSecret: APP_CLIENT_SECRET, poolId: USER_POOL_ID)
AWSCognitoIdentityUserPool.registerCognitoIdentityUserPoolWithConfiguration(serviceConfiguration, userPoolConfiguration: userPoolConfiguration, forKey: USER_POOL_NAME)
let pool = AWSCognitoIdentityUserPool(forKey:USER_POOL_NAME)
pool.delegate = self
self.storyboard = UIStoryboard(name: "Main", bundle: nil)
let credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: IDENTITY_POOL_ID, identityProviderManager:pool)
let configuration = AWSServiceConfiguration(region:.USEast1, credentialsProvider:credentialsProvider)
I also cannot access any DynamoDB data through my app.
Based on the console output, the registration process seems to work correctly, although I'm unsure about the sign-in process. It occurred to me that I had changed the region from EU-West-1, where the DynamoDB resources were stored, to US-East-1. In order to account for this change, I repeated the same steps I had intially taken to allow my app to access DynamoDB:
I created Auth and Unauth roles, both with access to the same actions as the role which had previously worked, but for the EU-West-1 resources instead.
I set these roles to the user pool I created when setting up registration under "unauthenticated role" and "authenticated role".
In case it makes a difference, I should note that I did not use the exact same sign-in process outlined in the example project I linked. Instead, I used the explicit sign in process, like so:
let name = usernameField.text!
let user = pool!.getUser(name)
lock()
user.getSession(name, password: passwordField.text!, validationData: nil, scopes: nil).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: {
(task:AWSTask!) -> AnyObject! in
if task.error != nil {
self.sendErrorPopup("ERROR: Unable to sign in. Error description: " + task.error!.description)
} else {
print("Successful Login")
dispatch_async(dispatch_get_main_queue()){
self.performSegueWithIdentifier("mainViewControllerSegue", sender: self)
}
}
self.unlock()
return nil
})
The methods lock(), unlock(), and sendErrorPopup() are strictly UI-related methods that I made so that the beginning and end of the sign-in process would be more visually clear. The console output always reads "successful login", but I am wondering if this code actually signs the user in correctly, since the error message makes it sound like the user might not be properly authorized.
It occurred to me that the US-West tables might not have been set up correctly, but I experience the same problem even when trying to create new tables, so I don't think that's the issue. Are there steps I might have missed as far as giving the user access to DynamoDB? Has the process changed with AWS Cognito's new beta user pool system?
EDIT 2:
I fixed the previous issue, and for a while, my app was working fine. However, it has suddenly stopped loading DynamoDB data when I sign in, and shows the error message: invalid login token. Can't pass in a Cognito token. Currently, my AppData code looks like this:
let serviceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: nil)
let userPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId:APP_CLIENT_ID, clientSecret: APP_CLIENT_SECRET, poolId: USER_POOL_ID)
AWSCognitoIdentityUserPool.registerCognitoIdentityUserPoolWithConfiguration(serviceConfiguration, userPoolConfiguration: userPoolConfiguration, forKey: USER_POOL_NAME)
let pool = AWSCognitoIdentityUserPool(forKey:USER_POOL_NAME)
pool.delegate = self
self.storyboard = UIStoryboard(name: "Main", bundle: nil)
self.credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: IDENTITY_POOL_ID, identityProviderManager:pool)
let manager = IdentityProviderManager(tokens: [NSString:NSString]())
self.credentialsProvider = AWSCognitoCredentialsProvider(regionType: .USEast1, identityPoolId: IDENTITY_POOL_ID, identityProviderManager: manager)
let configuration = AWSServiceConfiguration(region:.USEast1, credentialsProvider:credentialsProvider!)
AWSServiceManager.defaultServiceManager().defaultServiceConfiguration = configuration
...and my sign-in code looks like this:
if locked { return }
trimRegistrationValues()
let name = usernameField.text!
let user = pool!.getUser(name)
lock()
user.getSession(name, password: passwordField.text!, validationData: nil, scopes: nil).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: {
(task:AWSTask!) -> AnyObject! in
if task.error != nil {
self.sendErrorPopup("ERROR: Unable to sign in. Error description: " + task.error!.description)
} else {
print("Successful Login")
let loginKey = "cognito-idp.us-east-1.amazonaws.com/" + USER_POOL_ID
var logins = [NSString : NSString]()
self.credentialsProvider!.identityProvider.logins().continueWithBlock { (task: AWSTask!) -> AnyObject! in
if (task.error != nil) {
print("ERROR: Unable to get logins. Description: " + task.error!.description)
} else {
if task.result != nil{
let prevLogins = task.result as! [NSString:NSString]
print("Previous logins: " + String(prevLogins))
logins = prevLogins
}
logins[loginKey] = name
let manager = IdentityProviderManager(tokens: logins)
self.credentialsProvider!.setIdentityProviderManagerOnce(manager)
self.credentialsProvider!.getIdentityId().continueWithBlock { (task: AWSTask!) -> AnyObject! in
if (task.error != nil) {
print("ERROR: Unable to get ID. Error description: " + task.error!.description)
} else {
print("Signed in user with the following ID:")
print(task.result)
dispatch_async(dispatch_get_main_queue()){
self.performSegueWithIdentifier("mainViewControllerSegue", sender: self)
}
}
return nil
}
}
return nil
}
}
self.unlock()
return nil
})
I haven't changed anything between my app working and not working. I did cause a "too many password resets" error while testing the password reset functionality, but the issue persisted even when I created a new user account on my app, so I don't think that's the cause. Am I handling login correctly? If so, where should I look for other possible causes to this issue?
That exception is usually thrown if you've given Cognito a login but have not enabled your identity pool to consume that login provider. If you haven't, go to the Cognito Federated Identities console and turn on whichever provider you are trying to use (looks like User Pools), and this error should go away.
If you're certain you have set that up, can you give a code snippet of how you're setting the logins?
The key that you set the ID token against in logins should be of the format cognito-idp.<region>.amazonaws.com/<YOUR_USER_POOL_ID> not your USER_POOL_NAME. This blog along with the link in your post for our dev guide should explain the steps and code you need.
As for the solution to deprecated logins dictionary, you need to use this constructor to create the credentials provider. The identityProviderManager here should be an implementation of AWSIdentityProviderManager Protocol and the logins method should return the dictionary mapping for your provider name to the token. The credentials provider will call this method every time it needs the identity provider token. Check this answer for more details.

Google Endpoints with iOS Client : User has to sign in every time

I'm developing an iOS Application that uses Google Endpoints API. In order to authorise the requests, the user must sign in with his Gmail account on the first screen. I've managed to get this to work but the problem is that the user has to log in every single time he launches the app. Is there a way to have the session last a bit longer? For example, when using the Facebook SDK for iOS, once the user logs in with Facebook, the session stays active until the user explicitly logs out.
Thanks,
I've come up with what I consider to be a hack that solves this problem.
Step 1: After the user signs in with his/her Gmail account, save the authentication object properties to NSUserDefaults.
#objc(viewController:finishedWithAuth:error:)
func finishedWithAuth(viewController :GTMOAuth2ViewControllerTouch , auth:GTMOAuth2Authentication,error:NSError!){
self.dismissViewControllerAnimated(true, completion: nil);
if error != nil {
println("Authentication Failure: \(error.localizedDescription)");
}else{
GoogleEndpointAssistant.saveGTMOAuth2AuthenticationToUserDefaults(auth)
setAuthentication(auth)
}
GoogleEndpointAssistant.swift
class func saveGTMOAuth2AuthenticationToUserDefaults(auth : GTMOAuth2Authentication!){
assert(auth.parameters != nil)
assert(auth.parameters.count > 0)
auth.parameters.setValue(auth.tokenURL.absoluteString, forKey: "token_url")
auth.parameters.setValue(auth.redirectURI, forKey: "redirect_url")
let defaults = NSUserDefaults.standardUserDefaults();
defaults.setObject(auth.parameters, forKey: GMTOAuth2AuthenticationKey)
}
Step 2: Rebuild the auth object in viewDidLoad:
override func viewDidLoad() {
if let auth : GTMOAuth2Authentication = GoogleEndpointAssistant.rebuildGTMOAuth2AuthenticationFromUserDefaults(){
setAuthentication(auth)
}
}
GoogleEndpointAssistant.swift
class func rebuildGTMOAuth2AuthenticationFromUserDefaults()->GTMOAuth2Authentication?{
let defaults = NSUserDefaults.standardUserDefaults();
if let parameters = defaults.dictionaryForKey(GMTOAuth2AuthenticationKey){
let serviceProvider = parameters["serviceProvider"] as? String
let tokenURL = NSURL(string:parameters["token_url"] as String)
let redirectURL = parameters["redirect_url"] as String
let auth : GTMOAuth2Authentication = GTMOAuth2Authentication.authenticationWithServiceProvider(
serviceProvider,
tokenURL: tokenURL,
redirectURI: redirectURL,
clientID: GoogleCloudEndPointClientID,
clientSecret: GoogleCloudEndPointClientSecret) as GTMOAuth2Authentication
auth.userEmail = parameters["email"] as String
auth.userID = parameters["userID"] as String
auth.userEmailIsVerified = parameters["isVerified"] as String
auth.scope = parameters["scope"] as String
auth.code = parameters["code"] as String
auth.tokenType = parameters["token_type"] as String
auth.expiresIn = (parameters["expires_in"] as NSNumber).longValue
auth.refreshToken = parameters["refresh_token"] as String
auth.accessToken = parameters["access_token"] as String
return auth
}
return nil
}

Resources