Getting the logged in user info from ADAL on android - android

I am working with ADAL from
https://github.com/Azure-Samples/active-directory-android
My code mimics the sample very close
mAuthContext.acquireToken(ToDoActivity.this, Constants.RESOURCE_ID,
Constants.CLIENT_ID, Constants.REDIRECT_URL, Constants.USER_HINT,
new AuthenticationCallback<AuthenticationResult>() {
#Override
public void onError(Exception exc) {
if (mLoginProgressDialog.isShowing()) {
mLoginProgressDialog.dismiss();
}
Toast.makeText(getApplicationContext(),
TAG + "getToken Error:" + exc.getMessage(), Toast.LENGTH_SHORT)
.show();
navigateToLogOut();
}
#Override
public void onSuccess(AuthenticationResult result) {
if (mLoginProgressDialog.isShowing()) {
mLoginProgressDialog.dismiss();
}
if (result != null && !result.getAccessToken().isEmpty()) {
setLocalToken(result);
sendRequest();
} else {
navigateToLogOut();
}
}
});
I pass in the user's email address, but if the user changes it and uses a different one the ADAL library on the onSuccess never tells me the user changed it. The AuthenticationResult has a field calls mUserInfo that that should contain user's first name/last name email etc.
But for me every successful login mUserInfo=null.
Anyone know how to get ADAL to return a fully populated mUserInfo object?
thanks
Tom

Userinfo is constructed from the ID_token retuned from the server. In case of adfs blue (3.0), it does not return an ID_token and hence you cannot truly know what user signed in at the IDP. Adfs threshold supports ID_token if you can upgrade.

Related

Microsoft ADAL authentication on Android

I'm trying to create a SyncAdapter for Microsoft calendars and the first step is Authentication. i'm using com.microsoft.aad:adal:2.0.4-alphaand using this code for first authentication:
getAuthenticationContext().acquireToken(
mContextActivity,
Constants.SCOPES.split(" "),
null,
Constants.CLIENT_ID,
Constants.REDIRECT_URI,
PromptBehavior.Auto,
new AuthenticationCallback<AuthenticationResult>() {
#Override
public void onSuccess(final AuthenticationResult authenticationResult) {
if (authenticationResult != null && authenticationResult.getStatus() ==
AuthenticationResult.AuthenticationStatus.Succeeded) {
dependencyResolver = new ADALDependencyResolver(
getAuthenticationContext(),
resourceId,
Constants.CLIENT_ID);
token = authenticationResult.getToken();
UserInfo userInfo = authenticationResult.getUserInfo();
if (userInfo != null) {
userIdentifier = new UserIdentifier(userInfo.getUniqueId(),
UserIdentifier.UserIdentifierType.UniqueId);
}
}
}
#Override
public void onError(Exception t) {
Log.e("initialize", "onError : " + t.getMessage());
result.setException(t);
}
}
);
this works perfectly and after entering username and password i can get token.
BUT this is for sync adapter and at some point i need to get token silently. so i used this code:
public void getTokenSilent() {
getAuthenticationContext()
.acquireTokenSilent(Constants.SCOPES.split(" "),
Constants.CLIENT_ID,
userIdentifier,
new AuthenticationCallback<AuthenticationResult>() {
#Override
public void onSuccess(
AuthenticationResult authenticationResult) {
UserInfo userInfo = authenticationResult.getUserInfo();
}
#Override
public void onError(Exception e) {
Log.e("getTokenSilent", "onError : " + e.getMessage());
}
});
}
After executing this code i got the error:
AUTH_REFRESH_FAILED_PROMPT_NOT_ALLOWED Prompt is not allowed and failed to get token: ver:2.0.4-alpha
onError : Refresh token is failed and prompt is not allowed
how can i resolve this error and get or refresh token silently?
tnx in advance.
If you want to get the token silently, there are two ways for using Azure AD V2.0 endpoint.
First, acquire the access token and refresh token interactively, then get the access token in the cache or renew the access token using refresh token via acquireTokenSilent method.
Second is that the Azure AD V2.0 endpoint also support the Client Credentials flow(refer here) which normally used for the service daemon application. However the MSAL for android doesn't support this flow at present. You need to implement it yourself. You can follow this article about detail of this flow. And this flow only works for the Azure AD account.

How to check the authorization status using android-evernote sdk?

Im developing an android application which uses evernote android sdk for some evernote process.
The login is successfull and authorization is also working.
How can I check if the authorization status is valid or invalid after the login.
Based on following method
com.evernote.client.android.EvernoteSession.isLoggedIn()
It only returns the login status.It returns true if login was succesfull otherwise it returns false.
In ios-evenote sdk they have the variable
in the class -ENSession.h
with the help of property isAuthenticated we can find the the authorization status.
Like that i want to know the authorization status.For instance I was logged in today and gave authorization for 1 day and did not logout.After that I closed my app without using the logout session.
Tomorrow I want to check the status of authorization. How can I do that? Is there is any method available in the evernote android sdk?
You can use:
EvernoteSession.getInstance().isLoggedIn()
to get the current authentication status of the user. Just make sure you are using the most up to date (v2+) version of the SDK (available here: https://github.com/evernote/evernote-sdk-android)
Multiple examples in the readme for the SDK utilize this method for the purpose you describe including this one: https://github.com/evernote/evernote-sdk-android/blob/master/README.md#creating-a-note-asynchronously
Follow the steps to get the session status whether it is active or not
check the login status
if login success means then call any api method that is listing the notebooks,etc
If it is success means session is valid otherwise invalid session
For instance sample code is given below
final SessionCheckingCallback callback_final = callback;
if (!mEvernoteSession.isLoggedIn()) {
Log.d(SESSION_CHECK_TAG, "Session expired.Session not logged in");
callback.onSessionExpired();
}
try {
AsyncNoteStoreClient asyncNoteStoreClient = mEvernoteSession.getClientFactory().createNoteStoreClient();
asyncNoteStoreClient.listNotebooks
(
new OnClientCallback<List<Notebook>>() {
#Override
public void onSuccess(List<Notebook> data) {
//Session valid
callback_final.onSessionSuccess();
}
#Override
public void onException(Exception exception)
{
exception.printStackTrace();
if (exception instanceof EDAMUserException)
{
Log.d(SESSION_CHECK_TAG, "exception is EDAMUserException");
EDAMUserException eDAMUserException = (EDAMUserException) exception;
if (eDAMUserException.getErrorCode() == EDAMErrorCode.AUTH_EXPIRED) {
Log.d(SESSION_CHECK_TAG, "Session expired");
callback_final.onSessionExpired();
} else {
Log.d(SESSION_CHECK_TAG, "Session not expired");
callback_final.onSessionSuccess();
}
}
else
{
Log.d(SESSION_CHECK_TAG, "exception is not EDAMUserException");
Log.d(SESSION_CHECK_TAG, "Session expired");
callback_final.onSessionExpired();
}
}
}
);
} catch (Exception ex) {
ex.printStackTrace();
Log.d("Session check", "session expired due to exception ");
callback.onSessionExpired();
}

Linking Facebook to ParseUser

I am not sure if I am missing a step in the process of linking a Facebook account to an existing Parse User.
This is the code I am using, as per Parse.com
if (!ParseFacebookUtils.isLinked(currentUser)) {
ParseFacebookUtils.linkWithReadPermissionsInBackground(currentUser, getActivity(), null, new SaveCallback() {
#Override
public void done(ParseException ex) {
if (ex == null) {
if (ParseFacebookUtils.isLinked(currentUser)) {
Log.d("MyApp", "Woohoo, user logged in with Facebook!");
}
} else {
Log.e(TAG, ex.getMessage());
}
}
});
}
I am not receiving any type of error, and it will successfully open up the Facebook activity to accept/cancel giving access to my application. The issue that I am finding, is that the authData section inside my User record, inside Parse, is never populated.
What am I doing wrong that my Parse User is not receiving any authData?
Do you happen to add the code to fragment?
If you do that, you should consider about onActivityForResult.
As you know, onActivityForResult is not called normally.

Change password of parse user using parse SDK in Android

I am developing android application and using parse.com as back end storage. But I got stuck on change password. I am able to send the reset password mail using parse.com sdk to particular email. but I want to change the password using application as well without log enter code herein using old password.
Function to send mail:-
public void resetPassword() {
CustomProgressDialog.show(LoginActivity.this, "", getResources()
.getString(R.string.please_wait));
ParseUser.requestPasswordResetInBackground("test#gmail.com",
new RequestPasswordResetCallback() {
public void done(ParseException e) {
CustomProgressDialog.dismissMe();
if (e == null) {
// An email was successfully sent with reset
// instructions.
Toast.makeText(getApplicationContext(), getResources().getString(R.string.reset_password_sent), Toast.LENGTH_LONG).show();
} else {
// Something went wrong. Look at the ParseException
// to see what's up.
Toast.makeText(getApplicationContext(), getResources().getString(R.string.reset_password_fail), Toast.LENGTH_LONG).show();
}
}
}
);
}
And also able to launch the application from mail using declaring the permission in AndroidManifest.xml.
You can use for that next method ParseUser.setPassword().
Idea is next, if user is logged in then you don't need to check old password, because it was already entered and applied by Parse.com. So you will have 2 fields New Password and Confirm New Password. Users enters them and application changes it on server.
ParseUser parseUser = ParseUser.getCurrentUser();
parseUser.setPassword(password);
parseUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
if (null == e) {
// report about success
} else {
// report about error
}
}
});

Firebase: How to keep an Android user logged in?

I'm using Firebase SimpleLogin to enable Email / Password authentication. Creation of users and subsequent login is all working fine. However, whenever I leave the app (even if only for a few seconds) the user is never logged in on my return i.e...
authClient.checkAuthStatus(new SimpleLoginAuthenticatedHandler())...
Always returns a null user.
I am not logging out the user via the API. Also I have set the number of days the user is logged in to 21 in the Firebase console.
I have seen mention of a remember-me param in the JS docs, but I can't see any equivalent for Android / Java.
Wondering if I'm missing anything in the docs or if it's not possible for Android?
Thanks for your help,
Neil.
Edit: Added code sample.
User creation....
public void registerUserForChat(final MyApplication application, String email, String password) {
Firebase ref = new Firebase(FIREBASE_URL);
SimpleLogin authClient = new SimpleLogin(ref);
authClient.createUser(email, password, new SimpleLoginAuthenticatedHandler() {
#Override
public void authenticated(com.firebase.simplelogin.enums.Error error, User user) {
if(error != null) {
Log.e(TAG, "Error attempting to create new Firebase User: " + error);
}
else {
Log.d(TAG, "User successfully registered for Firebase");
application.setLoggedIntoChat(true);
}
}
});
}
User login....
public void loginUserForChat(final MyApplication application, String email, String password) {
Log.d(TAG, "Attempting to login Firebase user...");
Firebase ref = new Firebase(FirebaseService.FIREBASE_URL);
final SimpleLogin authClient = new SimpleLogin(ref);
authClient.checkAuthStatus(new SimpleLoginAuthenticatedHandler() {
#Override
public void authenticated(com.firebase.simplelogin.enums.Error error, User user) {
if (error != null) {
Log.d(TAG, "error performing check: " + error);
} else if (user == null) {
Log.d(TAG, "no user logged in. Will login...");
authClient.loginWithEmail(email, password, new SimpleLoginAuthenticatedHandler() {
#Override
public void authenticated(com.firebase.simplelogin.enums.Error error, User user) {
if(error != null) {
if(com.firebase.simplelogin.enums.Error.UserDoesNotExist == error) {
Log.e(TAG, "UserDoesNotExist!");
} else {
Log.e(TAG, "Error attempting to login Firebase User: " + error);
}
}
else {
Log.d(TAG, "User successfully logged into Firebase");
application.setLoggedIntoChat(true);
}
}
});
} else {
Log.d(TAG, "user is logged in");
}
}
});
}
So loginUserForChat method first checks to see if there is a logged in user and, if not, performs the login. Note that every time I start the app, the logging I see is....
Attempting to login Firebase user...
no user logged in. Will login...
User successfully logged into Firebase
If I exit the app, even for a few seconds, and return - I see the same logging.
One thing I noticed is that the call to checkAuthStatus does not take any user credentials - I assume it just checks for any locally logged in user?
Much appreciated.
Another way - try this code in your onCreate:
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
// User is signed in
Intent i = new Intent(LoginActivity.this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
This will keep the user logged in by taking the user to the Main activity directly without stopping at registration activity. so the user will be logged in unless the user click on signout.
[Engineer at Firebase] In order to transparently handle persistent sessions in the Firebase Simple Login Java client, you need to use the two-argument constructor which accepts an Android context, i.e. SimpleLogin(com.firebase.client.Firebase ref, android.content.Context context) every time you instantiate the Simple Login Java client.
See https://www.firebase.com/docs/java-simple-login-api/javadoc/com/firebase/simplelogin/SimpleLogin.html for the full API reference.
The proper way to do it is to use oAuth authentication:
1. The user logs in.
2. You generate an access token(oAuth2).
3. Android app saves the token locally.
4. Each time the comes back to the auth, he can use the token to to log in, unless the token has been revoked by you, or he changed his
password.
Luckily, firebase has an out of the box support for that, docs:
https://www.firebase.com/docs/security/custom-login.html
https://www.firebase.com/docs/security/authentication.html
You can do this by Using this Approach to escape logi page if User already logged in.
private FirebaseAuth auth;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
startActivity(new Intent(Login_Activity.this, Home.class));
finish();
}
setContentView(R.layout.activity_login_);
for those using Kotlin, to keep the user logged in just add in the onCreate function
if (auth.currentUser != null)
{
startActivity(Intent(this#Login, SellingPageHolderActivity::class.java))
finish()
}

Categories

Resources