I work on google app project and I am struggling a bit with java oauth library (1.10.1-beta).
I followed closely : http://code.google.com/p/google-oauth-java-client/wiki/OAuth2#Authorization_code_flow
Problem is that I dont know from where I should get userId or userEmail. I know there is userinfo API but I am actually trying to create Credentials, so I cannot access userinfo API AFIAK.
My application work nicely on localhost (because of test#example.com user is always there) but fails miserably when deployed in google engine environment (NullPointerException user.getUserId()).
// we ask for token because we got authCode
GoogleTokenResponse gTokenResponse = userUtils.getFlow().newTokenRequest(authCode).setRedirectUri(userUtils.getRedirectUri()).execute();
//trying to search for user email / id / whatever
User user = UserServiceFactory.getUserService().getCurrentUser();
//user is null -> nullPointerException is thrown
userUtils.getFlow().createAndStoreCredential(gTokenResponse, user.getUserId());
Could you please point out a flaw in my use-case or give me a hint ? I searched a lot in SDK samples,Stackoverflow and here but there is not many implementations.
PS: In method AuthorizationCodeFlow.createAndStoreCredential(...) is userId mandatory only when you use persistent storage for Credentials and yes i am using that so userId cannot be null in my case.
Thanks.
You are doing OAUTH (authorization) before you identified your user (authentication). You must redirect your user to the login page when he is not logged in :
UserServiceFactory.getUserService().getCurrentUser() == null
You do that by redirecting the user to the loginUrl :
String loginUrl = userService.createLoginURL(request.getOriginalRef().toString());
The next time the user arrives at your app, he will be logged in, and you can ask for the userId.
Related
I am trying to implement a feature for a user to change their password in their settings page when they are logged in, and I require the user's old password as well as the new password when they try to change it as an extra security measure. My problem is that I cannot find a way to verify if the user's old password is correct. Is there an easy way to do this?
I receive the entered form inputs on the server so the solution would have to be on the backend (node.js)
Many thanks
Though the accepted solution works, there is also a way to verify a user's password from the backend, using the Google Identity Kit REST API's "verifyPassword" endpoint (which has recently been renamed to "signInWithPassword", but works exactly the same):
HTTP POST https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[YOUR_FIREBASE_API_KEY]
{
email,
password,
}
If that endpoint doesn't return an error, that means the password is valid.
See this thread for more information.
You have to do it client side. This is not an operation that the admin SDK is designed to handle. You will ask the current user for the password and reauthenticate with it and then update password:
const cred = firebase.auth.EmailAuthProvider.credential(
firebase.auth().currentUser.email, oldPass);
firebase.auth().currentUser.reauthenticateWithCredential(cred)
.then(() => {
return firebase.auth().currentUser.updatePassword(newPass);
})
.catch((error) => {
// Some error.
});
So I have been stuck on this for a while, I'm trying to post from my web application (Spring boot) AUTOMATICALLY without any user interaction, NO POPUP LOGIN VIA FB OR AUTHORIZE FB ACTION nothing.
My application itself should do this. I achieved this by using :
public String postStatusOnPage(String message) {
if (socialFacebookConfiguration.isEnableWorkaroundAutoPost()) {
String id = facebook.pageOperations().post(new PagePostData(socialFacebookConfiguration.getPageId()).message(message));
log.log(Level.INFO, "Created New post id: " + id);
return id;
} else {
return null;
}
}
This works all ok. Bud , there is an issue and i dont know if my solution is really a right way to do it.
Im getting facebook The authentication has expired.
My access token that i have defined in application.properties
workaround.social.facebook.accessToken=...
Will expire. I dont know about how to refresh it. I have cheated a bit by using
https://developers.facebook.com/tools/explorer/
Question :
So How do I automatically get new access token? Is this a correct way of doing this OR is there better way? Is there a possibility to have access token that never expires?
Side note : MY application has OAuth2 login via google, bud I want application itself to do this, without any user being logged in(administrator as a human).
There is another token that i have , its app token
Bud this one does not work for posting to my page. On invocation throws :
faceboook An active access token must be used to query information
about the current user.
An App Token does not have any relation to a User or Page. You MUST use a Page Token to post to your Page, and you can use an Extended Page Token for that.
More information about Tokens: https://developers.facebook.com/docs/facebook-login/access-tokens/
On android client, I create Credentials, then choose account using AccountPicker and set the account name. On GAE, I have User parameter in every endpoint method. (I described it here)
Android Client ID, Web client ID and audiences are configured correctly.
On endpoint, the user is not null and has correct email set. But when I call user.getUserId() I get null. Is this user authenticated or not?... It really makes me nervous not to know that...
What you describe is odd, and I don't know why you get null when you call getUserId(), but never-the-less I would say, Yes, you are authenticated.
If you want to be sure, then you could try using that authentication from a web client - I read that once you have authenticated an Android user you are automatically given minimal account authentication for web too. So create a minimal servlet that includes the following code:
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
Load the page while signed in with the same account you authenticated from Android and see whether it acts like it already knows you, or whether it prompts the user as it would for a different, un-authenticated user.
This is a bug on google's side.
There seems to be a clunky workaround: save User to datastore and read it back.
I have a Java Web Application that gets information from the user. Before processing the information I wanted to make sure the email entered by the user belongs to the community.
I was originally going to have a file listing everyone int the community's email address. Upon submit, grab the email and ensure it exists in the master file.
Can anyone recommend how to do this with Google App Engine platform?
Thanks so much!
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
if (user == null) {
response.sendRedirect( "/login" );
}
out.print( user.getNickname() );
You can obtain the email address from the User class above. The code above checks if a user is already logged into the google account. There is Open authorization protocol that would enable you to see if the visitor is already logged into a site that supports oAuth protocol (like Facebook etc).
I'm trying to get friend list of users in my Android app. To do so I'm using:facebook-android-sdk-3.0.1.
The SDK comes with it's own loging/logout button so I used it. When I click login it handles the event(calls login screen asks for permission) so I have nothing to do. Right after login, onSessionStateChange function being called which is inside the A_class extends Fragment
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) { // Session open
getFriends(); // Call FQL codes...
} else if (state.isClosed()) { // Session closed
// After first login, It always coming here.Couse:Invalid access token.
}
}
I've followed the tutorials. I was able to: login > ask basic permissions > fetch the friend list(by using FQL) > logout.
After the first successfull login and authentication, If I Logout/Exit from the app, I'm not able to login again. In SDK's finishAuthorization it returns Invalid access token exception, which fails the session to open.
If I login my facebook account on browser and deauthorize the facebook application on my account, I'm able to login again and fetch friends. It looks like I have to refresh the access token or something... Thank you for any suggestions.
I've figguredout that the token is returning empty string "".
Do you try to re-authorize after logout ? Maybe the token expires. In my apps, I dont do a logout. The token is valid, till it expires. So in that case I login again :).
I can't say what the fix is to your exact issue but I remember having a similar problem with FB where the token existed but was invalid.
Basically what happens in the sdk, if I remember correctly, is this
FB auth -> have token? -> yes -> create session with token
As you can see in the above there is no step to check if the token is valid so it's always returning a session that has been closed.
You should try to forcefully flush the token from memory on logout thus avoiding the FB sdk giving you a Session with an invalid token.
The above is just a guess so take it with a pinch of salt.
First check the availability of your access token from Facebook debug tool from Here https://developers.facebook.com/tools/debug/access_token. This tool will provide you with some info about the access token provided like Time to Expire and Scopes ... etc
If the token is expired you have to refresh it (re-authorize it) using the graph api:
https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=app-id&client_secret=app-secret&fb_exchange_token=old_token
Just replace old_token in the URL with the expired access token and use your app_id and secret instead of client_id and client_secret respectively. The return value is a new token that you can use instead of the old one.
You can refresh the access token at the time you got the exception of invalid access token and replace it before logging in.