Cognito IDToken Renewal using RefreshToken - android

Hi I am android application developer , I am using cognito authentication mechanism for mobile app. Once i authenticate my user i get RefreshToken and IDToken. According to Amazon cognito it expire IDToken after exactly one hour.I am trying to get my session again to get token again and here is how i am trying to get it done.
String poolId = 'xxxxxx';
String clientId = 'xxxxxx';
String clientSecret = 'xxxxxx';
CognitoUserPool userPool = new CognitoUserPool(context, poolId, clientId, clientSecret,Regions.EU_WEST_1);
CognitoUser user = userPool.getUser();
user.getSessionInBackground(new AuthenticationHandler() {
#Override
public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
String idToken = userSession.getIdToken().getJWTToken();
Map<String, String> logins = new HashMap<String, String>();
logins.put("cognito-idp." + Constants.REGION + ".amazonaws.com/" + Constants.UserPool, userSession.getIdToken().getJWTToken());
credentialsProvider.setLogins(logins);
credentialsProvider.refresh();
}
#Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
Log.i("MQTT","Detail");
}
#Override
public void getMFACode(MultiFactorAuthenticationContinuation continuation) {
Log.i("MQTT","MFACode");
}
#Override
public void authenticationChallenge(ChallengeContinuation continuation) {
Log.i("MQTT","Challenge");
}
#Override
public void onFailure(Exception exception) {
Log.i("MQTT","Fail");
}
});
I have userpoolid and need to know where from i can get clientID and clientSecret.So that i get data in onSuccess callback and get IDToken.
Really thankful if someone can help out.
Thanks

Go to your user pool in cognito and click on the pool you want to
work on.
Under general settings, click on app clients.
Now click on add app client.
Give your app a name
Make sure the Generate client secret is selected.
Click on create client app.
Now you can note down the client id and client secret.
Docs: https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html

Related

AWS Cognito Unknown Error on signin

I'm getting an Unkown Error when I'm trying to signin to Cognito in AWS using android ( java ) code.
public void SignIn(String phoneNumber) {
final ClientConfiguration clientConfiguration = new ClientConfiguration();
// Create a CognitoUserPool object to refer to your user pool
CognitoUserPool userPool = new CognitoUserPool(_context, poolId, _clientId,
_clientSecret, clientConfiguration);
CognitoUser user = userPool.getUser(phoneNumber);
// Callback handler for the sign-in process
AuthenticationHandler authenticationHandler = new AuthenticationHandler() {
#Override
public void onSuccess(CognitoUserSession cognitoUserSession) {
// Sign-in was successful, cognitoUserSession will contain tokens for the user
Token = cognitoUserSession.getAccessToken();
}
#Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
// The API needs user sign-in credentials to continue
AuthenticationDetails authenticationDetails = new AuthenticationDetails(userId, _password, null);
// Pass the user sign-in credentials to the continuation
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
// Allow the sign-in to continue
authenticationContinuation.continueTask();
}
#Override
public void getMFACode(MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation) {
// Multi-factor authentication is required; get the verification code from user
multiFactorAuthenticationContinuation.setMfaCode("123");
// Allow the sign-in process to continue
multiFactorAuthenticationContinuation.continueTask();
}
#Override
public void onFailure(Exception exception) {
// Sign-in failed, check exception for the cause
Log.d("error:", exception.getMessage());
LoginController loginController = new LoginController(_this);
loginController.NavigateToLogin();
}
};
// Sign in the user
user.getSessionInBackground(authenticationHandler);
}
I've accepted all the default roles in IAM.
Signup and confirmation of the email works fine. it's just when I want to signin after authenticationContinuation.continueTask(); it's showing unknown error. any ideas? suggestions?
Turns out I was using a wrong poolid duh!
there is a pool id in federation pool as well and I was using that instead of the one in user pool

How to store and retrieve AWS Cognito JWT Token in Android

My Android app authenticates with Cognito in an AsyncTask and receives the JWT token as part of the CognitoUserSession. This is then set in the CognitoCachingCredentialsProvider using setLogins().
I would like to retrieve this JWT token in another AsyncTask. However getLogins() on the CognitoCachingCredentialsProvider is returning a size 0 Map.
What is the easiest way to get back the token? Should I store it in Shared Preferences again?
Get/SetLogins in the SDK just update a map inside the credentials provider, they don't save it long term. If you need to access it across threads at some arbitrary time, that would be a reasonable way to accomplish it. Otherwise, just use the exact same credentials provider and it'll be there.
CognitoCachingCredentialsProvider is actually using the shared preferences to save data, but getLogins is returning a size 0 hash.
The easy way to persist data (JWT) was the shared preferences in the AsyncTask doInBackgraound method and retrieve wherever it is required.
Could get these token(refresh token / access token / id token) from aws in login time and put in preference like following:
final AuthenticationHandler authenticationCallBackManager = new AuthenticationHandler() {
#Override
public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice) {
/*SharedPreferenceCacheManager.writeString(
LoginActivity.this,
"ACCESS_TOKEN",
userSession.getAccessToken().getJWTToken());*/
//System.out.println(userSession.getAccessToken().getJWTToken());//<<-------access token
/*SharedPreferenceCacheManager.writeString(
LoginActivity.this,
"REFRESH_TOKEN",
userSession.getRefreshToken().getToken());*/
//System.out.println(userSession.getRefreshToken().getToken());//<<---------refresh token
SharedPreferenceCacheManager.writeString(
LoginActivity.this,
"ID_TOKEN",
userSession.getIdToken().getJWTToken());
//System.out.println(userSession.getIdToken().getJWTToken());//<<-----------id token(this id uses Authorization in aws-side)
//....
}
#Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
AuthenticationDetails authenticationDetails = new AuthenticationDetails(
userId,
String.valueOf(editTextPassword.getText()), null);
//System.out.println(CognitoServiceConstants.AUTH_PARAM_USERNAME);
//System.out.println(CognitoServiceConstants.AUTH_PARAM_REFRESH_TOKEN);
// Pass the user sign-in credentials to the continuation
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
// Allow the sign-in to continue
authenticationContinuation.continueTask();
}
#Override
public void getMFACode(MultiFactorAuthenticationContinuation continuation) {
//....
}
#Override
public void authenticationChallenge(ChallengeContinuation continuation) {
//....
}
#Override
public void onFailure(Exception exception) {
//....
}
};

How to get password from aws cognito - android?

so im working with aws cognito, and im a bit confused on how to get the password?
If a user enters a password into an edit text, how do i get the password the user had entered when they signed up so i can compare the password they're logged in with to the password the registered with?
Here is the code i had to register my user:
userPool.signUpInBackground(username_ET.getText().toString(), password_ET.getText().toString(), userAttributes, null, signupCallback);
And here is the code i used to log in:
private AuthenticationHandler authenticationHandler = new AuthenticationHandler()
{
#Override
public void onSuccess(CognitoUserSession userSession, CognitoDevice newDevice)
{
Log.d(COGNITO_LOGIN,"Login success I think?!");
cognitoUser.getDetailsInBackground(getDetailsHandler);
//Here i need to compare passwords before i can move on.
}
#Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId)
{
Log.d(COGNITO_LOGIN,passwordET.getText().toString());
// The API needs user sign-in credentials to continue
AuthenticationDetails authenticationDetails = new AuthenticationDetails(userId, passwordET.getText().toString(), null);
// Pass the user sign-in credentials to the continuation
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
// Allow the sign-in to continue
authenticationContinuation.continueTask();
}
#Override
public void getMFACode(MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation) {
// Multi-factor authentication is required; get the verification code from user
multiFactorAuthenticationContinuation.setMfaCode("verificationCode");
// Allow the sign-in process to continue
multiFactorAuthenticationContinuation.continueTask();
}
#Override
public void authenticationChallenge(ChallengeContinuation continuation) {
}
#Override
public void onFailure(Exception exception)
{
// Sign-in failed, check exception for the cause
Log.d(COGNITO_LOGIN,"Login failed!");
Log.d(COGNITO_LOGIN,exception.getMessage());
exceptionMessage(exception.getMessage());
}
};
cognitoUser.getSessionInBackground(authenticationHandler);
With the authentication handler, i only need to pass in the correct username (or userID) to make the onSuccess run. Password isnt even required. So i am confused, to where the user must enter also the correct password in order for them to log in.
You don't need to compare passwords. When you sign up, Cognito stores a salt and a verifier for the password you signed up with. Cognito doesn't store your password in the form you entered it in but only a salt and verifier. When you use the code below, Cognito uses the Secure Remote Password protocol to match the verifier stored internally. Since we use the password you provided for computations, you cannot retrieve it. Note that in the onSuccess callback you will get tokens if the call is successful as noted below.
// Callback handler for the sign-in process
AuthenticationHandler authenticationHandler = new AuthenticationHandler() {
#Override
public void onSuccess(CognitoUserSession cognitoUserSession) {
// Sign-in was successful, cognitoUserSession will contain tokens for the user
}
#Override
public void getAuthenticationDetails(AuthenticationContinuation authenticationContinuation, String userId) {
// The API needs user sign-in credentials to continue
AuthenticationDetails authenticationDetails = new AuthenticationDetails(userId, password, null);
// Pass the user sign-in credentials to the continuation
authenticationContinuation.setAuthenticationDetails(authenticationDetails);
// Allow the sign-in to continue
authenticationContinuation.continueTask();
}
#Override
public void getMFACode(MultiFactorAuthenticationContinuation multiFactorAuthenticationContinuation) {
// Multi-factor authentication is required, get the verification code from user
multiFactorAuthenticationContinuation.setMfaCode(mfaVerificationCode);
// Allow the sign-in process to continue
multiFactorAuthenticationContinuation.continueTask();
}
#Override
public void onFailure(Exception exception) {
// Sign-in failed, check exception for the cause
}
};
// Sign-in the user
cognitoUser.getSessionInBackground(authenticationHandler);

Firebase authWithOauthToken is not working

I am developing an app in Android using firebase.I have created the login activity where i have a method that logs user in when they pass the credentials(user creation is already done).Then i will save the token recieved in onAuthenticated callback so that i can log user in automatically next time when he/she opens the app without asking to enter the credentials.
Here is the code
private void loginWithPassword(final String email, String password) {
progressDialog.show();
FirebaseConnections.getConnection().authWithPassword(email, password,
new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
// Authentication just completed successfully :)
IGStorePreference.getInstance().saveString(Constants.TOKEN, authData.getToken());
IGStorePreference.getInstance().saveString(Constants.UID, authData.getUid());
IGStorePreference.getInstance().saveString(Constants.PROVIDER, authData.getProvider());
dismissProgressDialog();
}
#Override
public void onAuthenticationError(FirebaseError error) {
// Something went wrong :(
dismissProgressDialog();
Snackbar.make(parentView, error.getMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
And then i check onCreate whether we have token token to log user in
private void checkIfTokenExistAndLogin() {
if (IGStorePreference.getInstance().isPrefExists(Constants.TOKEN)) {
progressDialog.show();
String provider = IGStorePreference.getInstance().getString(Constants.PROVIDER);
String token = IGStorePreference.getInstance().getString(Constants.TOKEN);
FirebaseConnections.getConnection().authWithOAuthToken(provider, token, new Firebase.AuthResultHandler() {
#Override
public void onAuthenticated(AuthData authData) {
IGStorePreference.getInstance().saveString(Constants.TOKEN, authData.getToken());
IGStorePreference.getInstance().saveString(Constants.UID, authData.getUid());
IGStorePreference.getInstance().saveString(Constants.PROVIDER, authData.getProvider());
dismissProgressDialog();
}
#Override
public void onAuthenticationError(FirebaseError firebaseError) {
dismissProgressDialog();
Snackbar.make(parentView, firebaseError.getMessage(), Snackbar.LENGTH_LONG).show();
}
});
}
}
But the problem is that i am getting an error while login user with authWithOAuthToken.Please help what i am missing.
This is the error i recieve everytime.
FirebaseError: Invalid authentication credentials provided.
authWithOAuthToken is used to login with a social provider. For example, user signs in with Google and gets an OAuth token returned from Google. Then app sends this OAuth token to Firebase auth server via authWithOAuthToken. User can log in after server verifies the OAuth token.
In your case, user logged in with email/password. The token you received was a Firebase auth token issued by Firebase auth server not an OAuth token issued by social provider.
Please refer to the doc for details: https://firebase.google.com/support/guides/firebase-android#sign_a_user_in_with_a_social_provider_numbered

How to get user information from twitter in android app?

I am integrating twitter in my android app. I am able to authorize the app for the user. Now, I am looking for the API which gives me logged users information like first name, last name, email, etc.
I had done this for facebook with
facebook.request("me");
Now how to get user info from twitter?
I am using twitter4j-core-android2.2.3.jar. Plz let me know is there a way to get user info.
Finally I got user information.
use the access token you get after
accessToken = twitterConnection.getOAuthAccessToken
(requestToken,editPinCode.getText().toString());
oHelper.storeAccessToken(accessToken);
Log.i("Access Token:", accessToken.getToken());
Log.i("Access Secret:", accessToken.getTokenSecret());
long userID = accessToken.getUserId();
User user = twitterConnection.showUser(userID);
user.getName();
Thanks.
There are a few tutorials here that can help you get an app running with twitter..
if you just need to retrieve info for a specific user, you can look here (includes source code):
Basic Adroid Twitter Integration
If you want to interact with twitter (e.g. post updates etc) then you will need to setup OAuth connection:
Android and Twitter integratin using OAuth
Twitter.getApiClient(session).getAccountService().verifyCredentials(true, false).enqueue(new Callback<User>()
{
#Override
public void success(Result<User> userResult)
{
try
{
User user = userResult.data;
// twitterImage = user.profileImageUrl;
} catch (Exception e)
{
e.printStackTrace();
}
}
#Override
public void failure(TwitterException e)
{
}
});
You cannot get Email from the twitter OAuth unless or untill your app is whitelisted.
For more Info
Email ID from Twitter
You can check bellow code: To get user info you can use Twitter Fabric SDK. Its documentation is here and here
twitterButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
AccountService ac = Twitter.getApiClient(result.data).getAccountService();
ac.verifyCredentials(true, true, new Callback<com.twitter.sdk.android.core.models.User>() {
#Override
public void success(Result<com.twitter.sdk.android.core.models.User> result) {
String imageUrl = result.data.profileImageUrl;
String email = result.data.email;
String userName = result.data.name;
System.out.println(imageUrl);
System.out.println(email);
System.out.println(userName);
}
#Override
public void failure(TwitterException e) {
Log.d("ls",e.getMessage());
}
});
}
#Override
public void failure(TwitterException exception) {
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.app_name),
Toast.LENGTH_SHORT).show();
}
});
Here twitterButton is
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
In this response you can get All credential without user Email.

Categories

Resources