I want to launch a new activity after successfully logging in using facebook login and maintain my session across all activities. I also don't want the log out in the next screen.
Samples for the new sdk don't provide any info about sessions so I am not sure how to go about this. Do we use AccessToken or Session class to maintain session and could anyone please provide links or examples for the same?
Once you initialize the Facebook SDK in your app and go through the login steps and get the user access token, your application will be logged in until you logout from user account via code.
And you can fetch the access token and check its status and validity (once the user logged in via your app) from any of your application activities via:
mAccessToken =AccessToken.getCurrentAccessToken(); // Which is a static function.
if(mAccessToken == null) // user are not logged in
{
// Proceed with your log in logic / code.
}
Related
Apparently the IOS version of this library AppAuth supports logging out using the end_session_endpoint but with the android version you are forced to implement one or find an alternative way of logging the user out.
Currently using the kotlin version of the library
on authorisationRequestBuilder if setPrompt method is not called, then during login you get the KMSI (keep me signed in) checkbox option.
Invalidating authState, persisted tokens and all other resources will not have an effect because hitting the authorise endpoint once again will automatically issue another token. This is because technically they are still logged in the server.
Using only the end_session_endpoint and no postLogoutRedirectUri provided. Is it possible to successfully log the user out and automatically redirect the user by closing the open chrome custom tabs immediately after the endpoint has been a success?
Currently calling the end_session_endpoint using AppAuth will successfully log the user out (You can see this in the open chrome custom tabs) but doesn't redirect or close the custom tabs.
How can this be achieved. I have configured the manifest with LogoutRedirectUriReceiverActivity but not sure how to initiate this. Other examples rely on the postLogoutRedirectUri being present.
Currently postLogoutRedirectUri doesn't exist on the discoveryDoc.
using IdentityServer4 you can include the idToken in the end session request. This way the user is logged out automatically without consent screens and such. Consequently you do not need a redirect after logout.
Your request would look like this:
GET /connect/endsession?id_token_hint=
source: https://identityserver4.readthedocs.io/en/latest/endpoints/endsession.html
Is it clear that the end_session_endpoint is a call to the server to logout? This sample code includes a callback (after end_session_endpoint) that removes any auth tokens stored within the app.
/*
* Do an OpenID Connect end session redirect and remove the SSO cookie
*/
fun getEndSessionRedirectIntent(metadata: AuthorizationServiceConfiguration,
idToken: String?): Intent {
val extraParams = mutableMapOf<String, String>()
val request = EndSessionRequest.Builder(metadata)
.setIdTokenHint(idToken)
.setPostLogoutRedirectUri(this.config.getPostLogoutRedirectUri())
.setAdditionalParameters(extraParams)
.build()
return authService.getEndSessionRequestIntent(request)
}
I am trying to set up a proper facebook login in my react native app. For now I have it working in a pure webview with oauth login to my server but I want to use the native facebook login to be able to take advantage of the facebook app.
I am using the following libraries:
Server side
https://github.com/FriendsOfSymfony/FOSUserBundle
https://github.com/hwi/HWIOAuthBundle
https://github.com/FriendsOfSymfony/FOSOAuthServerBundle
App side
https://github.com/magus/react-native-facebook-login
So my facebook login is perfectly functional on my website as well as on my app in a webview for OAuth by calling /oauth/v2/auth in a webview and handling the token.
But it is kinda messy because in the webview you have to type your full email + password combo.
So right now I'm just getting an authorization error when calling /login/facebook-check in a webview on the Login success event (by the native plugin), I could use some help to finish this.
Finally made it work. The hack was to use all the existing services to work together.
I made a custom controller. Some security checks are needed but still this works:
/**
* #Route("/api/facebook-connect/{accessToken}", name="api_facebook_connect", defaults={"_format" = "json"})
* #Rest\View()
*/
public function facebookLoginAction($accessToken, Request $request)
{
$token = new OAuthToken($accessToken);
$token->setResourceOwnerName('facebook');
$oauthUserProvider = $this->get('app.oauth.provider.user_provider');
$ressourceOwnerMap = $this->get('hwi_oauth.resource_ownermap.main');
$userChecker = new UserChecker();
$oauthProvider = new OAuthProvider($oauthUserProvider, $ressourceOwnerMap, $userChecker);
$token = $oauthProvider->authenticate($token);
$this->get('security.token_storage')->setToken($token);
$client = $this->get('doctrine.orm.entity_manager')->getRepository('AppBundle:Client')->findOneBy([], ['id' => 'DESC']);
$oauth2server = $this->get('fos_oauth_server.server');
$accessToken = $oauth2server->createAccessToken($client, $this->getUser(), 'user', 3600);
return $accessToken;
}
Will update this as I clean this up.
I'm not sure about how to properly handle the server-side part, however here are a few details about how we integrated Facebook login in one of our app:
We first started by using https://github.com/magus/react-native-facebook-login but later switched to https://github.com/facebook/react-native-fbsdk, which is maintained by Facebook and allow to access to other Facebook services (in particular, we used the Share API)
In both case (react-native-fbsdk or not), the flow was like this:
We have a Connect with Facebook button (a normal button, nothing fancy - we're not using the one provided by the modules).
When clicked, we call the Login method with the appropriate permissions. This should work out of the box, meaning that you'll have either a webview displayed (if you don't have the Facebook app) or the native Facebook app shown.
If the user declines the login to the app, nothing will happen.
If the user accepts, the app will receive the Access Token that can be used to issue calls to the Facebook API on the behalf of the user. This looks like this using react-native-fbsdk:
// This can be put in a Facebook login button component or a service,
// and should be called when the user wants to connect with Facebook
LoginManager.logInWithReadPermissions(permissions).then((result) => {
if (result.isCancelled) {
this.props.onCancel();
return;
}
AccessToken.getCurrentAccessToken().then((data) => {
this.props.onLogin(data);
});
}, (error) => {
console.warn('Facebook Error', error);
});
We then send the access token to our server which is able to fetch the profile of the user via the Facebook Graph API, creating a user account on the server if needed (i.e: if it's the first time the user log on).
// Called once we got the access token from the data in the previous
// step (this.props.onLogin(data)).
loginWithFacebook(facebookAccessToken) {
return fetch(`${apiHost}/api/login/facebook`, {
method: 'GET',
headers: {
// We pass the access token using the Authorization header:
Authorization: `Bearer ${facebookAccessToken}`,
},
}).then(() => {
// Whatever, for example get the user info returned by the server
// and store them.
});
}
On the server, we get the Access Token from the headers and use it to get the user profile (populating the account of the user for our app, for example with his avatar and name) and associate the user account with the facebook id of the user.
If the user have the Facebook app and already accepted the app, nothing will be asked to him the next time he tries to log in. You just click on the login button and get logged to the app :)
If the user don't have the Facebook app, the Facebook SDK always display a webview with the login page.
Hope this can help!
I am using Facebook new sdk 4.0.1, in that when i get log-in button changes to log-out and same button is used to logout without any code. but actually i want to do some coding at time of log-out. so how i get differentiate between these two things in that sdk?
How i declare logout method ?
You could check when the token changes, and if the new access token is null, the user just logged out.
new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken newAccessToken) {
if (newAccessToken==null)
//your code here!
}
};
Login Updates
Session Removed - AccessToken, LoginManager and CallbackManager classes supercede and replace functionality in the Session class.
Access Tokens - You can load AccessToken.getCurrentAccessToken with the SDK from cache or if the app is cold launched from an app bookmark. For instructions, see Facebook Login for Android, Get Current Token.
Login Button - The easiest way to add Login is to use the LoginButton in 4.x. See Facebook Login for Android, Add Facebook Login.
UserSettingsFragment class has been removed from the SDK.
LoginManager is a singleton instance, and works with the AccessToken's currentAccessToken. After login the SDK sets currentAccessToken. To get additional permissions call the logInWith... methods.
LogInWith... methods always open a prompt UI if necessary. There's no equivalent to the Session.openActiveSessionFromCache or Session.OpenActiveSession(Activity, boolean, StatusCallback). Instead, you should check AccessToken.getCurrentAccessToken() at onCreate(), and if not null, skip login.
AccessToken broadcast events when it is set, unset or updated.
Use the AccessTokenTracker to receive these events. See Facebook Login for Android, Track Access Tokens.
currentAccessToken automatically caches when the SDK sets it.
ProfileTracker.getCurrentProfile returns the current logged in user.
ProfileTracker returns events if the logged in user changes. see Facebook Login for Android, Track Current Profile.
CallbackManager.onActivityResult replaces Session.onActivityResult and UiLifecycleHelper.onActivityResult. See Facebook Login for Android, Register a Callback.
I want to create a User Session on Android so that i do not have to login every time.
What content should be stored in Shared Preferences so that i can authenticate every time my server gets a request from the user i can make sure people are not hacking into my system.
The users can login via the following in my app
Facebook
Google
Do i need to convert and store some encrypted data in Shared Preferences ?
Or just Storing the users Email or Username should be enough.
Its easy to store the credential in shared preferences So that when you splash screen comes it you can check it and redirect the user to the next screen without asking user to Login into google or facebook.
I have used the preferences to login using facebook and our own server. For that i hae stored one boolean variable that user is is login with facebook or our own server then if the user loged in with our own server then we have called the webservice in background with stored usercreadential in preferences and if user loged in with facebook then we have usered
if (Application.prefs.isFacebookLogin()) {
facebook = new Facebook(Application.APP_ID);
// Instantiate the asynrunner object for asynchronous api calls.
SessionStore.restore(facebook);
SessionEvents.addAuthListener(new FbAPIsAuthListener());
if (facebook.isSessionValid()) {
Application.prefs.setAccessTokenFb(facebook
.getAccessToken());
Application.prefs.setExpirationFB(facebook
.getAccessExpires());
}
// redirectHome();
// finish();
}
Here after that we have redirect user to the first screen if the creadential goes right.
We are implementing a project where the users post and get some information from a server. The scenario is that the user can create account/login both manually (giving email and password) and with facebook credentials using SSO. I implement mostly the Android part, but my questions are general.
Let’s say that I have a button where SSO is called prompting the user to give his credentials. So in order to create account what should I send to the server? Get the FB email of the user and set as password the Access Token that I received? Is that Access Token unique and permanent for every FB account, meaning the each time I use the same FB credentials I get the same Access Token?
Is there any additional work that needs to be done on the server side? Or can the server handle the users that use their FB accounts similarly as it handles the others?
Every clarification will be really helpful. Thank you in advance!
Are you using the Facebook Android SDK? If so, manual login (with user email/password) and SSO (via the Android Facebook app) are very similar, in particular with respect to token handling.
For example if you check out the example in the SDK (at sdk\examples\simple\src\com\facebook\android) you will see that the code does something like the following (split between three files).
private static final String TOKEN = "access_token";
private static final String EXPIRES = "expires_in";
private static final String KEY = "facebook-session";
Facebook session = new Facebook(APP_ID);
SharedPreferences savedSession = context.getSharedPreferences(KEY, Context.MODE_PRIVATE);
session.setAccessToken(savedSession.getString(TOKEN, null));
session.setAccessExpires(savedSession.getLong(EXPIRES, 0));
if (session.isSessionValid()) {
session.authorize(mActivity, mPermissions, new LoginDialogListener());
}
So you have to save the session token in SharedPreferences after each successful login (that is also in the example), but the token handling and login (authorize()) is the same for both manual and SSO login (depending on the activityCode parameter).
The token has a expiration timestamp, I guess the easy way is to generate the user account with the data fb will send you and store the fb token and expiration date as user attributes.