Getting email id value null as response during apple-authentication - ios

I'm implementing apple-authentication in react native using expo-apple-authentication package.
Below is the code which I'm calling on button's onPress.
async handleSocialLogin() {
const { mutate, BB, onSuccess, navigation } = this.props;
try {
const result = await AppleAuthentication.signInAsync({
requestedScopes: [
AppleAuthentication.AppleAuthenticationScope.FULL_NAME,
AppleAuthentication.AppleAuthenticationScope.EMAIL,
],
});
Alert.alert(JSON.stringify(result))
// signed in
} catch (e) {
Alert.alert(e)
if (e.code === 'ERR_CANCELED') {
// handle that the user canceled the sign-in flow
} else {
// handle other errors
}
}
}
It should return me authentication-token, Full_Name and Email which I requested in scope but It is giving me null for Full_Name and Email.

As per the documentation:
requestedScopes (AppleAuthenticationScope[]) (optional) - Array of user information scopes to which your app is requesting access. Note that the user can choose to deny your app access to any scope at the time of logging in. You will still need to handle null values for any scopes you request. Additionally, note that the requested scopes will only be provided to you the first time each user signs into your app; in subsequent requests they will be null.
You have probably already logged in once and didn't catch the logs. Subsequent log in will result in this data being null

Related

MSAL.NET OBO refresh token problems

I am trying to implement an OBO flow through to the graph API on a middle-tier API (.NET 5.0) using MSAL.NET. I'm running into two frustrating problems, and I can't find anyone having similar problems, so I think I'm misunderstanding something!
Problem 1: Whenever I call MSAL's GetAccountAsync, it always returns null when there should be an account loaded.
Problem 2: Whenever I call MSAL's AcquireTokenSilent, I always get the error "No refresh token found in the cache." even though I got one.
Here's what I have:
Once the web app authenticates, it passes through the token to a graph auth endpoint on the API:
var authenticationResult = await ClaimHelper.ClientApplication.AcquireTokenByAuthorizationCode(GraphHelpers.BasicGraphScopes, context.Code).ExecuteAsync();
var apiUserSession = await CouncilWiseAPIHelper.APIClient.Graph.AuthoriseUserAsync(authenticationResult.AccessToken);
which seems to work fine, and passes through a JWT to the API auth endpoint. The API implements an MSAL Confidential Client application and uses the SetBeforeAccess/SetAfterAccess token cache methods to save the cache to a database.
_msalClient = ConfidentialClientApplicationBuilder.Create(_graphConfig.ClientId)
.WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
.WithClientSecret(_graphConfig.ClientSecret)
.Build();
SetSerialiser(serialiser);
public void SetSerialiser(MSALTokenCacheSerialiser serialiser)
{
_msalClient.UserTokenCache.SetBeforeAccessAsync(serialiser.BeforeAccessCallbackAsync);
_msalClient.UserTokenCache.SetAfterAccessAsync(serialiser.AfterAccessCallbackAsync);
}
And the serialiser methods look like this:
public async Task BeforeAccessCallbackAsync(TokenCacheNotificationArgs notification)
{
GraphUserTokenCache tokenCache = await _graphUserTokenCacheRepository.GetByUserIdentifier(notification.SuggestedCacheKey);
if (tokenCache == null)
{
tokenCache = await _graphUserTokenCacheRepository.Get(notification.SuggestedCacheKey);
}
if (tokenCache != null)
{
notification.TokenCache.DeserializeMsalV3(tokenCache.Value);
}
}
public async Task AfterAccessCallbackAsync(TokenCacheNotificationArgs notification)
{
if (!notification.HasTokens)
{
// Delete from the cache
await _graphUserTokenCacheRepository.Delete(notification.SuggestedCacheKey);
}
if (!notification.HasStateChanged)
{
return;
}
GraphUserTokenCache tokenCache;
if (notification.SuggestedCacheKey == notification.Account.HomeAccountId.Identifier)
{
tokenCache = await _graphUserTokenCacheRepository.GetByUserIdentifier(notification.SuggestedCacheKey);
}
else
{
tokenCache = await _graphUserTokenCacheRepository.Get(notification.SuggestedCacheKey);
}
if (tokenCache == null)
{
var cache = notification.TokenCache.SerializeMsalV3();
tokenCache = new GraphUserTokenCache
{
Id = notification.SuggestedCacheKey,
AccountIdentifier = notification.Account.HomeAccountId.ToString(),
Value = cache
};
await _graphUserTokenCacheRepository.Add(tokenCache);
}
else
{
await _graphUserTokenCacheRepository.Update(tokenCache.Id, notification.TokenCache.SerializeMsalV3());
}
}
I can see the token BeforeAccess and AfterAccess methods being called, and I can see the caches being created in the database (encryption has been removed while I'm trying to track down this issue). If I inspect the serialised token cache being saved, it NEVER has a refresh token populated, but if I inspect the requests with fiddler I can see a refresh token was indeed provided.
Finally, here is the code for retrieving the access token which is called whenever a graph request is made:
public async Task<AuthenticationResult> GetAccessToken(string accountId, string jwtBearerToken)
{
try
{
IAccount account = null;
if (accountId.IsNotNullOrEmpty())
{
account = await _msalClient.GetAccountAsync(accountId);
}
var scope = _graphConfig.Scopes.Split(' ');
if (account == null)
{
var result = await _msalClient.AcquireTokenOnBehalfOf(scope,
new UserAssertion(jwtBearerToken))
.ExecuteAsync();
return result;
}
else
{
var result = await _msalClient.AcquireTokenSilent(scope, account)
.ExecuteAsync();
return result;
}
}
catch (MsalClientException ex)
{
ex.CwApiLog();
return null;
}
catch(Exception ex)
{
ex.CwApiLog();
return null;
}
}
When it's called with the jwtBearerToken, it will successfully call AcquireTokenOnBehalfOf() and the token is cached and a result returned, but when I come back to retrieve the account via GetAccountAsync() it always returns null even though I can see the token cache was loaded in BeforeAccessCallbackAsync().
Also, even if I call AcquireTokenSilent() immediately after acquiring the obo token with the account it just returned, I will get an exception saying there is no refresh token in the cache.
I am totally lost on what I'm doing wrong here, any help would be greatly appreciated.
I recently ran into the same problem while running a long runing OBO flow, MSAL has recently implemented an interface ILongRunningWebApi for these use cases you can go and see this new documentation
Here is an extract:
One OBO scenario is when a web API runs long running processes on
behalf of the user (for example, OneDrive which creates albums for
you). Starting with MSAL.NET 4.38.0, this can be implemented as such:
Before you start a long running process, call:
string sessionKey = // custom key or null
var authResult = await ((ILongRunningWebApi)confidentialClientApp)
.InitiateLongRunningProcessInWebApi(
scopes,
userToken,
ref sessionKey)
.ExecuteAsync();
userToken is a user token used to call this web API. sessionKey will
be used as a key when caching and retrieving the OBO token. If set to
null, MSAL will set it to the assertion hash of the passed-in user
token. It can also be set by the developer to something that
identifies a specific user session, like the optional sid claim from
the user token (for more information, see Provide optional claims to
your app). If the cache already contains a valid OBO token with this
sessionKey, InitiateLongRunningProcessInWebApi will return it.
Otherwise, the user token will be used to acquire a new OBO token from
AAD, which will then be cached and returned.
In the long-running process, whenever OBO token is needed, call:
var authResult = await ((ILongRunningWebApi)confidentialClientApp)
.AcquireTokenInLongRunningProcess(
scopes,
sessionKey)
.ExecuteAsync();
Pass the sessionKey which is associated with the current user's
session and will be used to retrieve the related OBO token. If the
token is expired, MSAL will use the cached refresh token to acquire a
new OBO access token from AAD and cache it. If no token is found with
this sessionKey, MSAL will throw a MsalClientException. Make sure to
call InitiateLongRunningProcessInWebApi first.
Hope this helps :)

How to know user is login by facebook or phone number in firebase ios (swift)? [duplicate]

I am using firebase from google and I have some trouble with user authentication. After logging with facebook I obtain FirebaseUser in AuthStateListener, but how can I detect if this user is logged via facebook or differently?
UPDATE
As #Frank van Puffelen said FirebaseAuth.getInstance().getCurrentUser().getProviderId()
should return "facebook", but in my case it returns "firebase". Now I cannot figure out what's the reason of this behavior. When I got FacebookToken I do something like this:
AuthCredential credential = FacebookAuthProvider.getCredential(facebookToken.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
}
}
});
And afterthat before onComplete() method is called, my AuthStateListener gets user which provider id is not "facebook" as it should be. Am I doing something wrong? I followed official google documentation
In version 3.x and later a single user can be signed in with multiple providers. So there is no longer the concept of a single provider ID. In fact when you call:
FirebaseAuth.getInstance().getCurrentUser().getProviderId()
It will always return firebase.
To detect if the user was signed in with Facebook, you will have to inspect the provider data:
for (UserInfo user: FirebaseAuth.getInstance().getCurrentUser().getProviderData()) {
if (user.getProviderId().equals("facebook.com")) {
System.out.println("User is signed in with Facebook");
}
}
In my app, I use Anonymous Firebase accounts. When I connect Firebase auth with a Facebook account or Google Account I am checking like the following:
for (UserInfo user: FirebaseAuth.getInstance().getCurrentUser().getProviderData()) {
if (user.getProviderId().equals("facebook.com")) {
//For linked facebook account
Log.d("xx_xx_provider_info", "User is signed in with Facebook");
} else if (user.getProviderId().equals("google.com")) {
//For linked Google account
Log.d("xx_xx_provider_info", "User is signed in with Google");
}
}
For me, the following solution is working.
First, get the firebase user object if you have'nt already:
FirebaseAuth mAuth = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = mAuth.getCurrentUser();
Now use the following on the FirebaseUser object to get the sign in provider:
firebaseUser.getIdToken(false).getResult().getSignInProvider()
Sources:
https://firebase.google.com/docs/reference/android/com/google/firebase/auth/FirebaseUser
https://firebase.google.com/docs/reference/android/com/google/firebase/auth/GetTokenResult.html
It will return password, google.com, facebook.com and twitter.com for email, google, facebook and twitter respectively.
Sharing for FirebaseAuth targeting version 6.x.x (Swift 5.0), year 2020:
I use Auth.auth().currentUser?.providerData.first?.providerID.
This will return password if logged in via email. And facebook.com if via Facebook.
There exist information in the responding Intent.
Refer to following snippet:
The responseCode is either "phone", "google.com", "facebook.com", or "twitter.com".
`import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.auth.IdpResponse;
.....
#Override
protected void onActivityResult(final int requestCode, int resultCode, Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
progressBar.setVisibility(View.VISIBLE);
IdpResponse response = IdpResponse.fromResultIntent(data);
if (resultCode == RESULT_OK) {
String providerCode = response.getProviderType();
...
}
}
Most recent solution is:
As noted here
var uiConfig = {
callbacks: {
signInSuccessWithAuthResult: function(authResult, redirectUrl) {
var providerId = authResult.additionalUserInfo.providerId;
//...
},
//..
}
and for display in page
firebase.auth().onAuthStateChanged(function (user) {
if (user) {
user.getIdToken().then(function (idToken) {
$('#user').text(welcomeName + "(" + localStorage.getItem("firebaseProviderId")+ ")");
$('#logged-in').show();
}
}
});

Access custom attributes for AWS Cognito User

I'm trying to get a custom attribute for a user in Cognito. In the AWS console I can see the custom attribute is set but in iOS when I make the call to AWSCognitoIdentityUser.getDetails().continueOnSuccessWith(block:) the response does not contain the custom attributes. Why would this be and how can I get access to them?
Here is how we accessed all attributed for cognito user.
//var params = {
// AccessToken: 'STRING_VALUE'
//};
cognitoidentityserviceprovider.getUser(params, function(err, data) {
if (err) {
callback(null, err);
} else {
callback(null, data);
}
});
Hope it helps.
EDIT1:
Also you need to ensure the custom attributes are with read permissions.
If you don't have read permissions, it will not be returned in your request.

Issues with OAuth 2.0 Library for Google Apps Scripts for MEETUP

I am using OAuth 2.0 Library for Google Spreadsheet for Meetup Api
Code.gs
function getMeetupService() {
return OAuth2.createService('meetup')
// Set the endpoint URLs, which are the same for all Google services.
.setAuthorizationBaseUrl('https://secure.meetup.com/oauth2/authorize')
.setTokenUrl('https://secure.meetup.com/oauth2/access')
// Set the client ID and secret, from the Google Developers Console.
.setClientId('.....')
.setClientSecret('......')
// Set the name of the callback function in the script referenced
// above that should be invoked to complete the OAuth flow.
.setCallbackFunction('authCallback')
// Set the property store where authorized tokens should be persisted.
.setPropertyStore(PropertiesService.getUserProperties())
.setTokenFormat(OAuth2.TOKEN_FORMAT.FORM_URL_ENCODED);
}
_eventId = null;
function startService(eventId) {
var meetupService = getMeetupService();
if (!meetupService.hasAccess()) {
var authorizationUrl = meetupService.getAuthorizationUrl();
return authorizationUrl;
} else {
//Yet to decide
}
return 123;
}
function authCallback(request) {
var meetupService = getMeetupService();
var isAuthorized = meetupService.handleCallback(request);
if (isAuthorized) {
//getAllDetails(_eventId);
} else {
return HtmlService.createHtmlOutput('Denied. You can close this tab');
}
}
Sidebar.html
$(function() {
checkService();
});
function checkService() {
google.script.run
.withSuccessHandler(function(url) {
if(url) {
$('body').append('Click here to Login into Meetup');
$('#run-get-details').attr("onclick", 'window.open("' + url + '")');
} else {
$('#run-get-details').attr("url", '');
}
$('#run-get-details').prop("disabled", false);
})
.withFailureHandler(failureHandler)
.startService($("#eventId").val());
}
function authCallback(request) {
alert(123);
}
Everything seems to be working till the link. Once the link is clicked it opens the authentication window of the meetup exactly i want. But then once I authorize the app in meetup and when it gets redirected to script.google.com
https://script.google.com/a/macros/{domain}/d/{PROJECT_ID}/usercallback?code={code}&state=ADEpC8wvspQd-+VXyQ0mOhYNenFu9Ib08hK6xfJ2gNJwcTxrIB4nVfphDyhejUHEMdgD0OhtwdcEs46KdhUZMD-Ekwftj3bzXwdi-mKc8PLKd7SsAYYqE-ZVZD2tm1HmyxtKYJCkoeg7R1K5DIMedYp38BiJ4F2Hbtei34fEdveObQhMSMDt1f2ufrmDzGh5W+fxdXMEmrfeCINO23hC8yV0JRXVDkErL3t8pQih8DicQoY6k2uqHThK8BqfSioBkgPZ0SPvj3Krtpgj9R+XWGtPqRRAwPum4k8etMROvy2DLT1ENNJdrVw
But then its throwing the error
The state token is invalid or has expired. Please try again.
Someone please help me in this.
So looking into this a bit further I found the issue. The Meetup server is changing the state token. If you copy your token from getAuthorizationUrl() and paste it into the state parameter in the url of the bad callback the Auth flow will successfully continue.
State Token made by Apps Script
ADEpC8zI8-E38GrIi2sB5Pf1xK2Hn-6XQ-SJLa0gmxos6z-hbvedTJ2UvXzSJxXbE_NfJlpHkOsjN4DLJ0sOGsYIZpTBc3OpAMWuoj-8UjUuKcTs1htZknyzv0QX9pPe-McxB_MC1fbGBjvrwEGP5_58tQdfRf3K70LURbe0cZ2qx_YK5xxN2qE
Returned State Token
ADEpC8zI8-E38GrIi2sB5Pf1xK2Hn-6XQ-SJLa0gmxos6z-hbvedTJ2UvXzSJxXbE+NfJlpHkOsjN4DLJ0sOGsYIZpTBc3OpAMWuoj-8UjUuKcTs1htZknyzv0QX9pPe-McxB+MC1fbGBjvrwEGP5+58tQdfRf3K70LURbe0cZ2qx+YK5xxN2qE

how to secure or set a rails style before_filter for all angular controllers?

I'm using angularjs for the front end and rails + devise for authentication on the backend.
On the front end I have added a responseInterceptor to redirect to the /#/sign_in page upon any 401 response from any xhr request and display a growl style pop-up message using toastr.
App.config(['$httpProvider', function ($httpProvider) {
$httpProvider.responseInterceptors.push('securityInterceptor');
}]);
App.factory('securityInterceptor', ['$injector', '$location', '$cookieStore', function ($injector,$location,$cookieStore) {
return function(promise) {
var $http = $injector.get('$http');
return promise.then(null, function(response){
if (response.status === 401) {
$cookieStore.remove('_angular_devise_user');
toastr.warning('You are logged out');
$location.path('/#/sign_in');
}
});
};
});
My problem is, when I click on a page that loads several xhr requests during the controllers initialization, for example:
var products = Product.query();
var categories = Category.query();
var variations = Variation.query();
These are needed for various navigation components and they all fire off in parallel, resulting in several duplicate growl-style messages.
Is there a way to make angular quit on the first 401 and stop execution of the rest of the controller from within the interceptor? In a traditional rails app, there would be a "before_filter" that stops regular execution, preventing the page and queries from loading... what's the best way to do this in angular?
I've been pondering about this problem for my own apps too. A sketch of my thoughts (NOT REAL IMPLEMENTATION, SO BEWARE):
A userData service keeps track of whether the user is logged in + other information (e.g. user name, real user name etc):
App.service("userData", function() {
var currentData = {
loggedIn: false
};
function getCurrent() {
return currentData;
}
// called when the user logs in with the user data
function loggedIn(userData) {
// the object is REPLACED to avoid race conditions, see explanation below
currentData = angular.extend({loggedIn: true}, userData);
}
return {
getCurrent: getCurrent,
loggedIn: loggedIn
};
});
The interceptors keep track of the currentData. If an interceptor receives HTTP 401 and the loggedIn flag is true, it changes the flag to false and redirects to the login view. If an interceptor receives HTTP 401 and the loggedIn flag is false, it does nothing besides rejecting the request, because another interceptor has done the view redirection.
When the user logs in, the currentData is replaced, so as to avoid situations with delayed responses (e.g. call1 and call2 are initiated, call1 responds 401; call2 also results in 401, but the delivery of the actual response is delayed; then the user logs in again; then call2 receives its 401; the second 401 should not overwrite the current state)
App.config(["$provide", "$httpProvider", function($provide, $httpProvider) {
$provide.factory("myHttpInterceptor", ["$q", "userData", "$cookieStore", "toastr", "$location",
function($q, userData, $cookieStore, toastr, $location) {
return {
request: function(config) {
config.currentUserData = userData.getCurrent();
return config;
},
responseError: function(rejection) {
if( rejection && rejection.status === 401 && rejection.config && rejection.config.currentUserData && rejection.config.currentUserData.loggedIn ) {
rejection.config.currentUserData.loggedIn = false;
$cookieStore.remove('_angular_devise_user');
toastr.warning('You are logged out');
$location.path('/#/sign_in');
}
return $q.reject(rejection);
}
};
}
]);
$httpProvider.interceptors.push("myHttpInterceptor");
});
Also note I am using the newer way to register interceptors, as $httpProvider.responseInterceptors seems to be deprecated.

Resources