Deleting a cognito user as admin - java

String userPoolId="testPoolID";
String username= "testuser";
String amazonAWSAccessKey="test access key";
String amazonAWSSecretKey="test secret key";
AdminDeleteUserRequest req = new AdminDeleteUserRequest();
req.setUsername(username);
req.setUserPoolId(userPoolId);
AWSCredentials credentials = new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey);
AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials);
credentialsProvider.getCredentials();
req.setRequestCredentialsProvider(credentialsProvider);
AWSCognitoIdentityProvider provider = new AWSCognitoIdentityProviderClient();
provider.adminDeleteUser(req);
This is the code snippet for deleting a user from cognito User pool. How we can delete a user from cogito without providing credentials using java ?

One way to do this would be to put this code in a lambda & expose it via API Gateway. Create another userpool for admins (its free!) & enable cognito userpool authorizers for your API. Now in your code, show a login screen (use Cognito's built-in UI) ,get the ID tokens and use this ID token while calling your API. This way your code will dynamically get tokens & so no hard-coded credentials.
Another way would be to use Cognito Federated Identities but in this case no lambda + API Gateway is needed. Again, create a userpool for Admins & add this as an Auth Provider in a Cognito Identity Pool. Now, login to the Admin userpool, get an Id token, use this token in the login map for the IdentityPool & get temporary credentials using GetCredentialsForIdentity. Just make sure that the Auth role for the Cognito Identity Pool has appropriate permissions to perform userpool actions.

Sorry its late, might be helpful for others who stumble on this.
If your code is in a lambda you can use the following code
AWSCognitoIdentityProviderClientBuilder.standard()
.withCredentials(DefaultAWSCredentialsProviderChain.getInstance())
.withRegion(region).build();
Note: Check if your lambda execution role is having access to cognito

Related

Using Cognito Authentication with Elastic Load Balancer

I have a ReactJS front end website which uses AWS Cognito for authentication, this is working fine, I can sign in, up, out, etc. My back end is a set of Java web services running in Docker containers in AWS Fargate all behind an Elastic Load Balancer.
I noticed that in the ELB, you can add Authentication to the listeners which will check the HTTP header for the jwt token and authenticate it before forwarding to the relevant micro service. I've come a cross an issue where when I set the 'Authenticate...' rule, it comes back with an error that I need to add a client secret. I can't add a client secret to my Cognito setup because I'm accessing it from ReactJS and apparently Javascript doesn't work with Cognito with Client Secret added.
So if I can't use this method, I need some way of authenticating HTTPS requests when they get to my Java microservices. From my Java service, it feels like I need to somehow access AWS Cognito to check the user session but that feels wrong.
Any ideas how this should work?
Thanks
You can consider to use pure JS to authenticate with AWS Cognito without client secret which is an optional. I did create a App Client without Client Secret and it did work.
Reference: https://docs.aws.amazon.com/cognito/latest/developerguide/authentication.html
// Amazon Cognito creates a session which includes the id, access, and refresh tokens of an authenticated user.
var authenticationData = {
Username : 'username',
Password : 'password',
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = {
UserPoolId : 'us-east-1_ExaMPle',
ClientId : '1example23456789'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
Username : 'username',
Pool : userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function (result) {
var accessToken = result.getAccessToken().getJwtToken();
/* Use the idToken for Logins Map when Federating User Pools with identity pools or when passing through an Authorization Header to an API Gateway Authorizer */
var idToken = result.idToken.jwtToken;
},
onFailure: function(err) {
alert(err);
},
});
Also, as you are using ReactJS, you can try Amplify:
https://aws-amplify.github.io/docs/js/authentication
I understand that while you have so many layers and sometimes you want to configure it as you want, you can try to make yourself a simple authenticating function with AWS Lambda.

Programmatically authenticate user with Keycloak in java

I have been looking through the Keycloak documentation but cannot see how to do this. With Java, I'd like to take a valid userid and password and then generate a token. How can I do this?
--EDIT 2018-08-31--
You can use the Authorization Client Java API. Once you have created an AuthzClient object, you can pass the username and password to the AuthzClient#authorization(username, password) or AuthzClient#obtainAccessToken(username, password) method to authenticate the user and get the access token (and/or ID token in the first case):
// create a new instance based on the configuration defined in keycloak-authz.json
AuthzClient authzClient = AuthzClient.create();
// send the authorization request to the server in order to
// obtain an access token granted to the user
AccessTokenResponse response = authzClient.obtainAccessToken("alice", "alice");
On a side note, if possible, you'd rather reuse one of the Keycloak Java Adapters to cover more features, such as other authentication methods (the user is typically redirected to Keycloack WUI where you can enforce very flexible authentication and authorization policies).

How to check user credentials in AZURE AD when acquired token using appId/appSecret (adal4j)?

I've created webapp (not native) in Azure AD. I have java code (adal4j) that
acquire token using appId/appSecret credentials:
String clientId = "xxxxxxxxxxxxxxxxxxxxxx";
String clientSecret = "yyyyyyyyyyyyyyyyyyyyyy";
String resourceUrl = "https://graph.windows.net";
String authorityUrl = "https://login.microsoftonline.com/zzzzzzzzzzzzzzzz/oauth2/authorize";
ExecutorService executorService = Executors.newFixedThreadPool(4);
Optional<UserInfo> userInfo = Optional.empty();
try {
AuthenticationContext authContext = new AuthenticationContext(authorityUrl, false, executorService);
Future<AuthenticationResult> future = authContext.acquireToken(resourceUrl, new ClientCredential(clientId, clientSecret), null);
AuthenticationResult result = future.get();
}
Now I would like to check if specified user/password combination is in Azure AD and if yes then get First and Last name of this user.
Is it possible to do this usinq acquired token ? How to write such code using adal4j ?
It sounds like what you're really trying to do is sign in a user and get their first/last name. As the comment said, the pattern suggested is not a valid one and would represent a security issue. Additionally, the use for clientId and clientSecret is not exactly for user credentials, but for app credentials. This is used for flows without user interaction for service/api applications, and doesn't sound like what you'll want.
Now, to achieve this you'll be using the OpenID Connect protocol. To simplify what will happen, your app (upon user trying to sign in) will redirect to the Microsoft sign in page (https://login.microsoftonline.com), enter their credentials and fulfill any other authorization requirements, consent to your app, and then redirected back. When they come back, your app will receive an ID Token which can be validated and used to get information about the user that has just sign in. During this time, Azure AD / Microsoft will also set a cookie on the browser so the user will get SSO across their account.
In terms of how to achieve this, I recommend following the ADAL4J Code Sample. This will get your app an ID Token, and also an Access/Refresh token that you can use to call the Microsoft Graph API. This API can also get you information about the user (basic profile info), but also their Office365, Intune, and Windows data.

Amazon Cognito developer authenticated identity with Java SDK

I am trying to authenticate a java app to AWS services using a developer-authenticated Cognito identity. This is very straightforward in the AWS mobile SDKs (documentation), but I can't seem to find the equivalent classes in the Java SDK.
The main issue I am having is that the Java SDK classes (such as WebIdentityFederationSessionCredentialsProvider) require the client code to know the arn of the role being assumed. With the mobile SDK, it uses the role configured for the federated identity. That's what I'd prefer to do, but it seems the Java SDK doesn't have the supporting classes for that.
The last comment from Jeff led me to the answer. Thanks Jeff!
String cognitoIdentityId = "your user's identity id";
String openIdToken = "open id token for the user created on backend";
Map<String,String> logins = new HashMap<>();
logins.put("cognito-identity.amazonaws.com", openIdToken);
GetCredentialsForIdentityRequest getCredentialsRequest =
new GetCredentialsForIdentityRequest()
.withIdentityId(cognitoIdentityId)
.withLogins(logins);
AmazonCognitoIdentityClient cognitoIdentityClient = new AmazonCognitoIdentityClient();
GetCredentialsForIdentityResult getCredentialsResult = cognitoIdentityClient.getCredentialsForIdentity(getCredentialsRequest);
Credentials credentials = getCredentialsResult.getCredentials();
AWSSessionCredentials sessionCredentials = new BasicSessionCredentials(
credentials.getAccessKeyId(),
credentials.getSecretKey(),
credentials.getSessionToken()
);
AmazonS3Client s3Client = new AmazonS3Client(sessionCredentials);
...
If that's the route you want to go, you can find this role in the IAM console, named Cognito_(Auth|Unauth)_DefaultRole. These are what Cognito generated and linked to your pool, and you can get the ARN from there.
This blog post may be of some assistance. All of the APIs the SDK uses to communicate with Cognito to get credentials are exposed in the Java SDK, you just need to use your own back end to get the token itself. Once you have it, you can set the logins the same way you normally would with another provider and it'll all work.

How to use JGit to push changes to remote with OAuth access token

I am able to push to remote with this piece of code
return git.push().setCredentialsProvider(new UsernamePasswordCredentialsProvider(user, password)).setRemote("origin").call();
I also am able to get oauth access token with all necessary scopes. How do I push with access token?
You need to pass a UsernamePasswordCredentialsProvider with the token as its user name.
String remoteUrl = "https://${token}#github.com/user/repo.git";
CredentialsProvider credentialsProvider = new UsernamePasswordCredentialsProvider("${token}", "");
git.push().setRemote(remoteUrl).setCredentialsProvider(credentialsProvider).call();
The above can at least be used to authenticate with a GitHub repository. Though, I can't say if this scheme works generally.

Categories