unable to read data from decoded token jwt verify [duplicate] - jwt

This question already has an answer here:
How to get user id using jwt token
(1 answer)
Closed 2 years ago.
jwt.verify(token,process.env.SECRETKEY, function(err,decodedToken){
console.log(decodedToken);
})
Console output
{ email: 'm.blal#gmail.com', iat: 1601341321 }
how can I read the value of email from decoded token?

Attach the email to the request, then you can access that value from the controller
jwt.verify(token,process.env.SECRETKEY, function(err,decodedToken){
if(err) throw new ForbiddenException('Invalid token');
req.user = decodedToken //Attach token payload to request
})
You can use that value later on the controller using req.user or creating a decorator (I prefer this).

Related

how to use firebase phone auth without create new uid [duplicate]

This question already has answers here:
Firebase phone Auth for Android , Can we just verify phone number without creating a user account
(3 answers)
Closed 3 years ago.
How to use firebase auth with phone number to verify phone number without create new uid i want to know just if the input code is correct or not
this the code that i used but it creates new uid
manualVerification() {
print("My Id" + verificationId);
FirebaseAuth.instance
.signInWithPhoneNumber(verificationId: verificationId, smsCode: smsCode)
.then((user) {
print("Verification Successful");
print("$user");
setState(() {
showStatus=3;
});
widget.onVerificationSuccess();
}).catchError((error) {
print("Verification Failed Due to $error");
widget.onVerificationFailure();
});
}
The whole point of Firebase Authentication is to create a user account with a unique ID. There's no way to separate out the process that just verifies the phone number.

How to get the Authentication Provider for actions-on-google on Node using account linking with Auth0?

I have Javascript App running under Node v8.11.2 which uses the Actions-On-Google library. I'm using the V2 API. I have account linking set up with Auth0 and am using the SignIn helper intent. Auth0 is set up to use Google, Facebook and Twitter.
The scopes I use are OPENID, OFFLINE_ACCESS, PROFILE and EMAIL.
Everything is working fine and when the User is authenticated I get an Access Token returned.
My question is, how do I get the Authentication Provider that was selected by the User so that I can use the Access Token correctly to retrieve profile elements such as the display name, email address etc??
The signin object passed to the Sign In Confirmation intent handler just contains the following regardless of the provider selected: -
{"#type":"type.googleapis.com/google.actions.v2.SignInValue","status":"OK"}
Any help greatly appreciated as I have a deadline and this is driving me a bit crazy now!
Thanks,
Shaun
If your question is about how to get the required information when you have your accessToken available then you could use what is shown in this answer.
In node this looks like that:
let link = "https://www.googleapis.com/oauth2/v1/userinfo?access_token="+accessToken;
return new Promise(resolve => {
request(link,(error, response, body) => {
if (!error && response.statusCode === 200) {
let data = JSON.parse(body);
let name = data.given_name ? data.given_name : '';
conv.ask(new SimpleResponse({
speech: "Hello "+ name + "!",
text: "Hello "+ name + "!"
}));
resolve();
} else {
console.log("Error in request promise: "+error);
resolve();
}
})
})
Everything you need should be in the data object.
Hope it helps.

Firebase signInWithCredential failed: First argument "credential" must be a valid credential

I am using the react-native-facebook-login package to log users in. Currently the flow is working well and after the user enters their details, I successfully see an object returned with their information.
When I try and create an account in Firebase with signInWithCredential, I receive the following error message:
signInWithCredential failed: First argument "credential" must be a valid
I can't seem to find a breakdown of how that credential needs to be passed - is it a string, an object, an array etc. Is it just the token or do I need to pass other details (i.e. the provider)?
The credentials object I am currently getting back has:
permission: Array
token: String
tokenExpirationDate: String
userId: String
Any help would be much appreciated - thanks!
Feeling pretty pleased - finally cracked the nut.
They key bit is the token needs to be changed first before being a relevant credential. See code below:
onLogin={function(data){
let token = firebase.auth.FacebookAuthProvider.credential(data.credentials.token);
firebase.auth().signInWithCredential(token)
.then((user) => {
console.log(user)
}).catch((err) => {
console.error('User signin error', err);
});
}}
to answer your question, based on the documentation of firebase:
where GoogleAuthProvider could be any of your setup / supported auth providers
// Build Firebase credential with the Google ID token.
var credential = firebase.auth.GoogleAuthProvider.credential(id_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
On a side note, as you are using react-native and firebase, did you already try react-native-firestack? makes a lot of things easier.

profile.providerId returns firebase instead of the social provider name [duplicate]

This question already has an answer here:
Firebase returns multiple IDs, Which is unique one?
(1 answer)
Closed 6 years ago.
I've successfully create authentication using Twitter with Firebase, but when I do (as indicated here):
if (user != null) {
user.providerData.forEach(function (profile) {
console.log("Sign-in provider: "+profile.providerId)
});
}
it prints out firebase. I expected to read twitter. How do I know which provider the user signed in with)?
Suppose you have this as you refrence variable
var authObj = $firebaseAuth(ref);
And Your using this in your init funtion to check if user is logged in or not
authObj.$onAuth(authDataCallback);
then you should try this for getting provider name and other details
function authDataCallback(authData) {
if (authData) {
console.log(authData.provider);
}
}
Hope it will help you out :)

Facebook4J support for exchanging access-tokens

I'm looking for a way to exchange short-lived access tokens for long-lived access tokens in our backend as described by Facebook here. How to do this with facebook4j?
I have done something like this to exchange old token for new token:
private AccessToken refreshToken(Facebook facebook, AccessToken currentToken) throws Exception {
String clientId = configuration.getString(ConfigurationKeys.SOCIAL_FACEBOOK_CLIENTID);
String clientSecret = configuration.getString(ConfigurationKeys.SOCIAL_FACEBOOK_CLIENTSECRET);
Map<String, String> params = new HashMap<String, String>();
params.put("client_id", clientId);
params.put("client_secret", clientSecret);
params.put("grant_type", "fb_exchange_token");
params.put("fb_exchange_token", currentToken.getToken());
RawAPIResponse apiResponse = facebook.callGetAPI("/oauth/access_token", params);
String response = apiResponse.asString();
AccessToken newAccessToken = new AccessToken(response);
facebook.setOAuthAccessToken(newAccessToken);
return newAccessToken;
}
I think this can be done after each login so the access token is refreshed even if it still valid - you will just get newer token with 60 days of validity.
What do you think?
I am extending the Facebook class. The method they provided don't work. So I wrote another function which does gives a long lived token but it's somehow invalid ( I tried testing the new token with token_debug and tried to generate client_code with it)! I will update you if I get to work it out. If you can solve it, please update me.
Please remember I didn't clean up the code as I am still writing on it.
public function GetExtendedAccessToken()
{
//global $CONFIGURATIONS;
//$info=$this->api($path,'GET',$args);//doesn't work as api overrides method to post
$string=file_get_contents("https://graph.facebook.com/oauth/access_token?client_id=".$this->getAppId()
."&client_secret=".$this->getAppSecret()
."&fb_exchange_token=".$this->getAccessToken()
."&grant_type=fb_exchange_token"
."&redirect_uri=".$redirectUri);
var_dump($string);
$tokenInfo=explode('&',$string);
$exAccessToken=str_replace('access_token=', '', $tokenInfo[0]);
$expiresAt=str_replace('expires=', '', $tokenInfo[1]);
echo "expires in ". (time()-$expiresAt);
var_dump($exAccessToken);
return $exAccessToken;
}
It works now. Some times I get an error for not providing redirect_uri.