ADAL for iOS exception with a different user sign-on - ios

I am using the ADAL iOS library for Azure authentication. However, I am having a problem if I first signed on with one account, and then sign-out and sign-in with another account. I get the following error, even though I set 'AD_PROMPT_ALWAYS'.
2015-08-31 12:50:39.939 PortalDev[908:174411] ADALiOS [2015-08-31 11:50:39 - xxx-xxx-xxx-xxx-xxx] ERROR: Error raised: 19. Additional Information: Domain: ADAuthenticationErrorDomain ProtocolCode:(null) Details:Different user was authenticated. Expected: 'aaa#xxx.com'; Actual: 'bbb#xxx.com'. Either the user entered credentials for different user, or cookie for different logged user is present. Consider calling acquireToken with AD_PROMPT_ALWAYS to ignore the cookie.. ErrorCode: 19.
2015-08-31 12:50:39.943 PortalDev[908:174411] ADAL Error: 19, Different user was authenticated. Expected: 'aaa#xxx.com'; Actual: 'bbb#xxx.com'. Either the user entered credentials for different user, or cookie for different logged user is present. Consider calling acquireToken with AD_PROMPT_ALWAYS to ignore the cookie. (status: 2)
I cleared the cache, and tried and cleared the cookies I think:
if (allItems.count > 0) {
[cache removeAllWithError:&error];
if (error) {
CLSNSLog(#"Error clearing cache: %#", error.errorDetails);
} else {
CLSNSLog(#"Items removed.");
}
} else {
CLSNSLog(#"Was no user cached.");
}
NSHTTPCookieStorage* cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* cookies = cookieStorage.cookies;
if (cookies.count)
{
for(NSHTTPCookie* cookie in cookies)
{
CLSNSLog(#"Deleting Auth Cookie %#.", cookie.name);
[cookieStorage deleteCookie:cookie];
}
CLSNSLog(#"Auth Cookies cleared.");
}
But I don't think there were any cookies to clear.
The username is pre-filled when I get the logon webpage. I thought it worked fine a few weeks/months ago, but now there seems a problem. I build the library fresh today from the latest GitHub source.
Any suggestions how I can make switching user name possible?

The error message says:
Expected: 'aaa#xxx.com'; Actual: 'bbb#xxx.com'
That indicates that a userId parameter is being passed to acquireToken. That would cause the username field in the sign-in page to be prefilled. However, the error is saying that when the user signed in they changed the username field to a different user. Because you asked for a specific user but did not get a token for that user, acquireToken returns an error. See this answer for more detail:
ADAL iOS - Different user was authenticated. Expected userA#mydomain.com, actual userB#mydomain.com

Related

Firebase : Facebook authentification with Firebase token not working

I'm trying to get working Facebook authentification in my app.
I'm following instructions here : https://firebase.google.com/docs/auth/ios/facebook-login
When I clicked on the Facebook login button, everything is working fine : the user is logged. In the facebook login delegate method, it is ok :
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!)
In this method, I have to create a Firebase token to authenticate finally with Firebase (step 5). This is what I do :
let credential = FacebookAuthProvider.credential(withAccessToken:
FBSDKAccessToken.current().tokenString)
Auth.auth().signIn(with: credential) { (user, error) in
if let error = error {
print(error.localizedDescription)
self.errorServer()
} else {
FitUtils.setFitUser(user: user)
}
}
The problem : My credential variable is not nil, everything is working, but when i'm calling Auth.auth().signIn(...), the method throwns the error variable, and user is nil.
I don't have many information about the error :
An internal error has occurred, print and inspect the error details
for more information.
And
error NSError domain: "FIRAuthErrorDomain" - code: 17999 0x0000604000640630
I suspect an error about the Facebook API key or something like that in the Firebase console, but I already checked everything is fine.
Any idea ?
EDIT
I found an explicit description of the error :
UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={
code = 400;
errors = (
{
domain = global;
message = "Unsuccessful debug_token response from Facebook: {\"error\":{\"message\":\"(#100) You must provide an app access token or a user access token that is an owner or developer of the app\",\"type\":\"OAuthException\",\"code\":100,\"fbtrace_id\":\"GkGVPPBP7vo\"}}";
reason = invalid;
}
);
message = "Unsuccessful debug_token response from Facebook: {\"error\":{\"message\":\"(#100) You must provide an app access token or a user access token that is an owner or developer of the app\",\"type\":\"OAuthException\",\"code\":100,\"fbtrace_id\":\"GkGVPPBP7vo\"}}";
}}}}
(lldb)
Finally found an answer thanks to this post :
https://github.com/firebase/FirebaseUI-iOS/issues/83#issuecomment-232523935
I have to disable the option "Is App Secret embedded in the client?" in the Facebook console :
Hope this helps.
On the Facebook Developer site, navigate to:
Settings > Advanced > Security > Require App Secret
Set to YES.
Fixed it for me.
The following worked for me:
Go to android/app/src/main/res/values/strings.xml. Make sure you have the following line in your <resources>:
<string name="facebook_app_id">FACEBOOK*APP*ID</string>
where FACEBOOK*APP*ID is the your app ID from developers.facebook.com/apps
In my case, there was set wrong App secret in Firebase 🤷🏻‍♂️
Go to the Firebase console and choose the project.
Under Project shortcuts choose Authentication.
Select Sign-in method tab.
In Sign-in providers click on Facebook to edit.
Set the correct App secret from your Facebook app.

Google OAuth 2 access token not working as expected some hours after authorizing

I'm using the Google Identity Platform's OAuth 2.0 flow to authorize a javascript/HTML teacher observation form to write to a Google Sheets document. Everything is working well most of the time; however, last night one of our principals hit the following error:
"Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project."
I determined that he had launched the observation tool in the afternoon, and now maybe five hours later was trying to click the submit button. My hunch was that the token had expired, but from Google's documentation it seems like the JS auth library is meant to handle refreshing the access token as necessary - I believe it's not actually possible to get a refresh token to do anything manually.
I'm using what is essentially the sample auth code, and the app responds to being signed out appropriately. That is, if I sign out in another tab, the submit button is disabled and the sign-in button appears again. Assuming token expiration is the issue here, any ideas on the correct way to identify if the token has expired and how to request a new one, ideally without user interaction? Or if it's not an expiration issue, what else could it be? This user has successfully submitted data in earlier observations; it was just this one time when he waited ~5 hours (potentially losing internet connectivity / sleeping his laptop) during that time.
Here's the auth code:
var clientId = ""; //id removed
var discoveryDocs = ["https://sheets.googleapis.com/$discovery/rest?version=v4"];
var scopes = "https://www.googleapis.com/auth/spreadsheets";
var authorizeButton = document.getElementById('authorize-button');
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
function initClient() {
gapi.client.init({
discoveryDocs: discoveryDocs,
clientId: clientId,
scope: scopes
}).then(function () {
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
});
}
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
document.getElementById('submit').disabled = false;
findRow(); //find the empty row once we're logged in
} else {
authorizeButton.style.display = 'block';
document.getElementById('submit').disabled = true;
}
}
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
Thank you!
Similar issues that i had resulted in issues from that Authorized Javascript origins.
"In the Authorized JavaScript origins field, enter the origin for your app. You can enter multiple origins to allow for your app to run on different protocols, domains, or subdomains. You cannot use wildcards. In the example below, the second URL could be a production URL." taken from https://developers.google.com/identity/sign-in/web/devconsole-project.If prompt to view task came from an email, the email origin must be verified -or- the device is used for multiple accounts, the token will not stay. If the api is being improperly used, it will allow functionality for a short period of time , then fail.
This may be useful, in the authflow, you do not have scope or id in options
/** * Initiate auth flow in response to user clicking authorize button. * *
#param {Event} event Button click event. */ function
handleAuthClick(event) {
gapi.auth.authorize( {client_id: '[#app:client_id]', scope:
["googleapis.com/auth/calendar"], immediate: false}, handleAuthResult);
return false; }
I believe How to refresh expired google sign-in logins? had the answer I needed. Since all of my API calls happen at once, I added a new Date() when the page loads, a second new Date() when the submission flow begins, and if they are more than 45min (2,700,700ms) apart, I use gapi.auth2.getAuthInstance().currentUser.get().reloadAuthResponse() to force an access token refresh, as documented at https://developers.google.com/identity/sign-in/web/reference#googleuserreloadauthresponse.
Hopefully Google will eventually update their documentation to reflect this now-necessary step when using the auth2 flow vs the older auth flow.
Time will tell if this actually solved the issue, but I'm hopeful!
I hope it helps you friend that error is because you have the wrong time, you go to date and time settings then press synchronize now.

Is anonymous auth enabled by default?

I have failed to find some info on this, but it seems that even though I do not force the user to auth(⚠️) at all, it seems as if I call FIRAuth.auth()?.currentUser at least a few seconds after startup, I will get a valid anonymous user back. Does the Firebase SDK log the current user in behind the scenes, or is an unauthed user always regarded anonymous?
⚠️ auth as in:
FIRAuth.auth()?.signInAnonymously() { (user, error) in
if error != nil {
print("Sign in anonymously failed: \(error)")
return
}
if let user = user {
print("user: \(user), is anon: \(user.isAnonymous), uid: \(user.uid)")
self.user = user
}
}
Update 1: It seems I may be wrong, or there is something else important here. It might be the case where a device that has previously signed in will subsequently always (or something... maybe using keychain etc) be treated as signed in, even if app is deleted between runs. Investigating...
Update 2: So after some investigation 🕵🏻 it seems that if we don't sign the user out specifically, the user will likely remain signed in forever OR at least a long time. Even between installs... I swear I tried to delete then install, and the user was still signed in...
No, you must enable anonymous authentication in the Firebase console in the 'Authentication' tab, under 'Sign In Method'

How to force Google OAuth popup in Firebase when user already authenticated previously?

Whenever a user has previously authenticated with Google, it automatically defaults to logging them in with THAT account on subsequent attempts. I want to eliminate this and force the popup/redirect so that a user with multiple google accounts can choose which one to use. How?
Background:
The automatic logging in feature is proving problematic for me as I have a whitelisted set of e-mails for users allowed to use my app. If a Google user chooses the wrong account when first logging in, they can't go back and choose the one associated to their whitelisted e-mail.
Just as #nvnagr said, you can do this with the following code:
var provider = new firebase.auth.GoogleAuthProvider();
provider.setCustomParameters({
'prompt': 'select_account'
});
But I think you need to update the firebase version to 3.6.0 something.
Google supports a parameter in authentication url to deal with this issue.
If you add prompt=select_account in your request to Google authentication, it'll force the user to do an account selection. See the details and other values of prompt.
https://developers.google.com/identity/protocols/OpenIDConnect#authenticationuriparameters
I'm not sure if there is an easy way to add this parameter through firebase api.
When you're calling the oAuth function, you can pass a third options parameter to make the authentication last for the session only. This should solve your problem. Docs
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.authWithOAuthPopup("google", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
}, {
remember: 'sessionOnly'
});

Unauthenticated user to authenticated user on AWS Cognito

My code is here: code
Reposted because I wanted to ask a more direct question. How do I switch between unauthenticated user and authenticated? My unauthenticated seems cached and I've used these methods:
[credentialsProvider clearCredentials];
[credentialsProvider clearKeychain];
before the rest of my api code and it still doesn't work. Any help is appreciated
Note: I know it's not working because I make a call using lambda right after I switch up my configuration/credentials provider and only authorized users should be able to call this method.
EDIT #behrooziAWS answer:
API CODE:
id<AWSCognitoIdentityProvider> identityProvider = [[DeveloperIdentityProviderClass alloc] initWithRegionType:AWSRegionUSEast1
identityId:nil
identityPoolId:#"SOMEIDENTITYPOOLID"
logins:#{#"MYIDENTITYPROVIDERNAME": #"MYUSERNAME"}
providerName:#"MYIDENTITYPROVIDERNAME"
];
[credentialsProvider setIdentityProvider:identityProvider];
[credentialsProvider setLogins:#{#"MYIDENTITYPROVIDERNAME": #"MYUSERNAME"}];
[[credentialsProvider refresh] continueWithBlock:^id(BFTask *task){
[self testAuth];
return [BFTask taskWithResult:nil];
}];
Full Error:
BusyTime[27043:7097936] AWSiOSSDKv2 [Verbose] AWSURLResponseSerialization.m line:87 | -[AWSJSONResponseSerializer responseObjectForResponse:originalRequest:currentRequest:data:error:] | Response body: [{"message":"The security token included in the request is invalid."}]
2015-10-20 08:51:17.280 BusyTime[27043:7097936] Error: Error Domain=com.amazonaws.AWSLambdaErrorDomain Code=0 "The operation couldn’t be completed. UnrecognizedClientException" UserInfo=0x7ff27ab41150 {NSLocalizedFailureReason=UnrecognizedClientException, responseStatusCode=403, message=The security token included in the request is invalid., responseHeaders={type = immutable dict, count = 6,
IMPORTANT EDIT: I've hardcoded my refresh to use a working token and identityId. so:
self.identityId = #"someID";
self.token = #"someToken";
return [super getIdentityId];
and then ALL my code is working. But obviously this isn't sustainable, I need to be able to make a call to aws lambda to refresh my credentials. But when I set my identity provider, and set my login, I think it's changing me to my authenticated version, but I need to be in unauthenticated to call aws lambda. Please refer to my code link above and take a look at my refresh method to understand what I'm poorly trying to describe. Also please let me know if this should go in a new thread as this is a slightly different question. Not so familiar with stackoverflow's policies on questions.
Another error: [{"Message":"User: arn:aws:sts::445291524102:assumed-role/Cognito_BusyTimeAuth_Role/CognitoIdentityCredentials is not authorized to perform: lambda:InvokeFunction on resource: arn:aws:lambda:us-east-1:445291524102:function:login"}], SO now I'm assuming my auth provider for my refresh which is incorrect login flow. I'm thinking that I switch this up so that I login in my API class. When I return my identity ID and token, I save them to keychain. Finally, I use the above API code to switch my logins and in my refresh method, I simply return what I found in my keychain. The only problem is I'm not sure if this flow is correct because it doesnt actually "refresh" as I'm not calling my backend. I was wondering if I could wrap the refresh by changing back and forth from my unauth role to my auth role but this seems messy.
[credentialsProvder clearKeychain] will clear the identityId, credentials and any logins, so clearCredentials is unnecessary: clearKeychain Documentation
Normally you don't want to clear your identity id when you transition to an authenticated user. If you simply add your provider and valid login token to the logins map and call [credentialsProvider refresh], you will become authenticated with the same identity id. From that point forward, you will only be able to access that identity if you provide a valid login token. If you want to switch identities by logging out and then login as a authenticated user, that is when you use clearKeychain.

Resources