Login with Facebook in react native return "The App_id in the input_token did not match the Viewing App" - reactjs

I come to you after hours of research.
I have created my facebook account with the application I am working on and also my firebase account that I have linked through the OAuth redirection URI to the configuration of your Facebook application.
But I always get the same mistake. Do you have any leads? Knowing that my APP_ID is the same in the code, on facebook developers and Firebase. And that I redirected the URI of firebase in facebook developpers.
Here is my code :
async function loginWithFacebook(){
await Facebook.initializeAsync({
appId : '1027709424451081'});
const {type,token} =
await Facebook.logInWithReadPermissionsAsync({
permissions:['public_profile'],
});
if (type === 'success') {
const credential = firebase.auth.FacebookAuthProvider.credential(token);
Firebase.auth().signInWithCredential(credential)
.then(user => { // All the details about user are in here returned from firebase
console.log('Logged in successfully', user)
})
.catch((error) => {
console.log('Error occurred ', error)
});
}
}
Thanks in advance for all suggestions.

When using the function "signInWithCredentials" you need to pass the auth also which you will get by
const auth = getAuth()
and then after getting the credentials
signInWithCredential(auth, credential)

Related

AWS Amplify + React Authentication Issue (Not getting JWT value after Auth.signIn() on Sign)

hope you all are well. I am working on a React project with a serverless backend in AWS Amplify. Facing an issue with the authentication which is blocking me to use admin action queries. The problem is the following:
I am getting "Uncaught (in promise) No current user" or "Uncaught (in promise) The user is not authenticated" after using the Auth.SignIn() method. I need to get the JWT value from Auth.currentAuthenticatedUser() and sign in correctly in order to perform administrative tasks (which require authentication).
The code for this is:
try {
const user = await Auth.signIn(username, password);
console.log(user); //prints the CognitoUser object.
console.log(Auth.currentAuthenticatedUser()); //throws any of the two errors mentioned above.
} catch (error) {
console.log(error);
}
When I implemented this previously, I was able to get the JWT token with the following method after authentication. That function is:
export const getJWT = async () => {
try{
const userCurrentSession = await Auth.currentSession();
const accessToken = userCurrentSession.getAccessToken();
const JWTvalue = accessToken.getJwtToken();
return JWTvalue;
}catch(error){console.log(error)}
};
I would be highly obliged if someone helps in resolving this problem. Thanks in advance.
Replace the lines inside of try block with the following:
const user = await Auth.currentAuthenticatedUser();
const JWTvalue = user.signInUserSession.getAccessToken().getJwtToken();
return JWTvalue;

MSAL: InteractionRequiredAuthError: no_tokens_found: No refresh token found in the cache. Please sign-in

Here's the bit of code that I was working on. I am using MSAL for two SSO apps on same domain for example https://some-domain.com/app1 and https://some-domain.com/app2 and please see the code snippet below.
App 1 seems to be fine it allows user to sign in correctly.However, on app2 when I reload the page it throws an error
MSAL: InteractionRequiredAuthError: no_tokens_found: No refresh token
found in the cache. Please sign-in.
I have used instance.acquireTokenRedirect,acquireTokenSilent and identityInstance.loginRedirect() but nothing seemed to work. Any ideas please share. Thanks.
const [userName, setUsername] = useState<string | undefined>()
useEffect(() => {
const fetchDetaiils = async () => {
if (inProgress === InteractionStatus.None) {
try {
const signedInUser = identityInstance.getAllAccounts()[0]
const resp = await identityInstance.acquireTokenSilent({
scopes: ['user.read'],
account,
})
const token: Token = resp?.idTokenClaims
setUsername(token.email)
} catch (err: unknown) {
if (err instanceof Error) {
console.log(err)
if (err?.name === 'InteractionRequiredAuthError') {
// await instance.acquireTokenRedirect(loginRequest)
}
}
}
}
}
fetchDetaiils()
As described in these Microsoft Docs, SSO between apps requires the use of either the login_hint or sid (session ID) parameters in the silent request.
The values of login_hint and sid can be extracted from the ID Token that is obtained in App 1. For more information, please consult the MSAL Browser Login Docs

How to get user profile URL of Facebook with Firebase Authentication?

I follow the docs of Firebase for Facebook login, it work but i don't see anything relate user profile link of Facebook, Am i missing something?
code in the docs of Firebase.
import { getAuth, signInWithPopup, FacebookAuthProvider } from "firebase/auth";
const auth = getAuth();
signInWithPopup(auth, provider)
.then((result) => {
// The signed-in user info.
const user = result.user;
// I don't see any properties in user relate with user profile link of Facebook
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
const credential = FacebookAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
// ...
})
.catch((error) => {
console.log(error.message)
// ...
});
There is no such URL provided. I suggest reviewing the documentation for the User interface and its UserInfo parent interface to find out what sort of data you have access to after the user signs in.

Django backend authentication with NextJS frontend form - best practices

I have an API hub that I've built in Django and a frontend end application I've built in NextJS. I'm currently working on authenticating to the Django API in Nextjs and I'm curious about best practices.
Currently, the NextJS app posts the users username/password to an endpoint. This endpoint either returns the users token or the error illustrating the issue.
React
const login = async () => {
let token = await axios.post('/api/accounts/', {
email: email,
password: password
}).then(r => r.data.token).catch(function (error) { console.log(error) })
if (token) {
router.push({
pathname: '/home/',
query: { token: token },
})
}
}
nexjs server api/accounts
export default async (req, res) => {
if (req.method === 'POST') {
try {
// retrieve payment intent data
const {data} = await axios.post('https://website/api/api-token-auth/', req.body)
res.status(200).send(data)
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message })
}
} else {
res.setHeader('Allow', 'POST')
res.status(405).end('Method Not Allowed')
}
}
Django API
#csrf_exempt
#api_view(["POST"])
#permission_classes((AllowAny,))
def obtain_auth_token(request):
email = request.data.get("email")
password = request.data.get("password")
if email is None or password is None:
return Response({'error': 'Please provide both email and password'},
status=HTTP_400_BAD_REQUEST)
user = authenticate(email=email, password=password)
if not user:
return Response({'error': 'Invalid Credentials'},
status=HTTP_404_NOT_FOUND)
token, _ = Token.objects.get_or_create(user=user)
return Response({'token': token.key},
status=HTTP_200_OK)
Once I receive the token I push the user to the homepage.
My questions are:
Is how I'm authenticating users a good way to do this? Am I overlooking something? This is the first time I've attempted to authenticate to something I've built so I want to get this right.
How should I store this token? What is "best practice" when it comes to authentication creds? I've thought about passing the token around to every component that needs it. I've also peeked at using LocalStorage but again am unsure what most people do in these situations.
Any help you all can provide would be much appreciated!
Thanks in advance!

Firebase Login Popup closes automatically on Heroku

We are using FireBase login for our app in React and the flow seems to be working fine on localhost.
But when we deploy our app on Heroku, the login with google window appears on screen and closes almost instantaneously.
Here's my auth.js
export function loginWithGoogle (email, pw) {
const provider = googleAuthProvider;
return firebaseAuth().signInWithPopup(provider)
.then(saveUser)
.catch(error => console.log(error));
}
Here's login.js
handleGoogleLogin = e => {
e.preventDefault();
loginWithGoogle()
.then(response => {
// This gives you a Google Access Token. You can use it to access the Google API.
console.log("After auth...",response);
//const TOKEN = response.credential.accessToken;
console.log("result...", response);
//TODO: Need to call ConsumeSafe API to store the user details
console.log("invoking getUser");
getUser(response.data.user.Email).
then((res) =>{
this.props.loginHandler(res);
});
})
.catch(error => {
console.log("Error in popup...",error);
this.setState(setErrorMsg("Invalid username/password."));
});
};
However none of the files catch any error but the window closes.
On my google dev console, I went to Credentials > Oauth2 Web client and added my heroku app url under authorized javascript origins. Still the same result
You need to add your domain to the Authorized domains in the firebase console.
Steps:
Visit your firebase console
Go to your firebase project
Go to Authentication -> Sign in method
Scroll down and you will see a list of Authorized domains
Add your domain address to the list and save it
This should solve your problem.

Resources