Example usage for com.amazonaws.services.identitymanagement AmazonIdentityManagementClient createAccessKey

List of usage examples for com.amazonaws.services.identitymanagement AmazonIdentityManagementClient createAccessKey

Introduction

In this page you can find the example usage for com.amazonaws.services.identitymanagement AmazonIdentityManagementClient createAccessKey.

Prototype

@Override
public CreateAccessKeyResult createAccessKey(CreateAccessKeyRequest request) 

Source Link

Document

Creates a new AWS secret access key and corresponding AWS access key ID for the specified user.

Usage

From source file:ch.cyberduck.core.iam.AmazonIdentityConfiguration.java

License:Open Source License

@Override
public void create(final String username, final String policy, final LoginCallback prompt)
        throws BackgroundException {
    if (log.isInfoEnabled()) {
        log.info(String.format("Create user %s with policy %s", username, policy));
    }/*from  w  w w .jav a2 s  . c  om*/
    this.authenticated(new Authenticated<Void>() {
        @Override
        public Void call() throws BackgroundException {
            // Create new IAM credentials
            final AmazonIdentityManagementClient client = new AmazonIdentityManagementClient(
                    new com.amazonaws.auth.AWSCredentials() {
                        @Override
                        public String getAWSAccessKeyId() {
                            return host.getCredentials().getUsername();
                        }

                        @Override
                        public String getAWSSecretKey() {
                            return host.getCredentials().getPassword();
                        }
                    }, configuration);
            try {
                // Create new IAM credentials
                User user;
                try {
                    user = client.createUser(new CreateUserRequest().withUserName(username)).getUser();
                } catch (EntityAlreadyExistsException e) {
                    user = client.getUser(new GetUserRequest().withUserName(username)).getUser();
                }
                final CreateAccessKeyResult key = client
                        .createAccessKey(new CreateAccessKeyRequest().withUserName(user.getUserName()));
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Created access key %s for user %s", key, username));
                }
                // Write policy document to get read access
                client.putUserPolicy(new PutUserPolicyRequest(user.getUserName(), "Policy", policy));
                // Map virtual user name to IAM access key
                final String id = key.getAccessKey().getAccessKeyId();
                if (log.isInfoEnabled()) {
                    log.info(String.format("Map user %s to access key %s",
                            String.format("%s%s", prefix, username), id));
                }
                PreferencesFactory.get().setProperty(String.format("%s%s", prefix, username), id);
                // Save secret
                PasswordStoreFactory.get().addPassword(host.getProtocol().getScheme(), host.getPort(),
                        host.getHostname(), id, key.getAccessKey().getSecretAccessKey());
            } catch (AmazonClientException e) {
                throw new AmazonServiceExceptionMappingService().map("Cannot write user configuration", e);
            } finally {
                client.shutdown();
            }
            return null;
        }
    }, prompt);
}

From source file:org.akvo.flow.InstanceConfigurator.java

License:Open Source License

public static void main(String[] args) throws Exception {

    Options opts = getOptions();/*  w  w  w .j  av  a  2  s .c om*/
    CommandLineParser parser = new BasicParser();
    CommandLine cli = null;

    try {
        cli = parser.parse(opts, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(InstanceConfigurator.class.getName(), opts);
        System.exit(1);
    }

    String awsAccessKey = cli.getOptionValue("ak");
    String awsSecret = cli.getOptionValue("as");
    String bucketName = cli.getOptionValue("bn");
    String gaeId = cli.getOptionValue("gae");
    String outFolder = cli.getOptionValue("o");
    String flowServices = cli.getOptionValue("fs");
    String alias = cli.getOptionValue("a");
    String emailFrom = cli.getOptionValue("ef");
    String emailTo = cli.getOptionValue("et");
    String orgName = cli.getOptionValue("on");
    String signingKey = cli.getOptionValue("sk");

    File out = new File(outFolder);

    if (!out.exists()) {
        out.mkdirs();
    }

    Map<String, AccessKey> accessKeys = new HashMap<String, AccessKey>();
    String apiKey = UUID.randomUUID().toString().replaceAll("-", "");

    AWSCredentials creds = new BasicAWSCredentials(awsAccessKey, awsSecret);
    AmazonIdentityManagementClient iamClient = new AmazonIdentityManagementClient(creds);
    AmazonS3Client s3Client = new AmazonS3Client(creds);

    // Creating bucket

    System.out.println("Creating bucket: " + bucketName);

    try {
        if (s3Client.doesBucketExist(bucketName)) {
            System.out.println(bucketName + " already exists, skipping creation");
        } else {
            s3Client.createBucket(bucketName, Region.EU_Ireland);
        }
    } catch (Exception e) {
        System.err.println("Error trying to create bucket " + bucketName + " : " + e.getMessage());
        System.exit(1);
    }

    // Creating users and groups

    String gaeUser = bucketName + GAE_SUFFIX;
    String apkUser = bucketName + APK_SUFFIX;

    // GAE

    System.out.println("Creating user: " + gaeUser);

    GetUserRequest gaeUserRequest = new GetUserRequest();
    gaeUserRequest.setUserName(gaeUser);

    try {
        iamClient.getUser(gaeUserRequest);
        System.out.println("User already exists, skipping creation");
    } catch (NoSuchEntityException e) {
        iamClient.createUser(new CreateUserRequest(gaeUser));
    }

    System.out.println("Requesting security credentials for " + gaeUser);

    CreateAccessKeyRequest gaeAccessRequest = new CreateAccessKeyRequest();
    gaeAccessRequest.setUserName(gaeUser);

    CreateAccessKeyResult gaeAccessResult = iamClient.createAccessKey(gaeAccessRequest);
    accessKeys.put(gaeUser, gaeAccessResult.getAccessKey());

    // APK

    System.out.println("Creating user: " + apkUser);

    GetUserRequest apkUserRequest = new GetUserRequest();
    apkUserRequest.setUserName(apkUser);

    try {
        iamClient.getUser(apkUserRequest);
        System.out.println("User already exists, skipping creation");
    } catch (NoSuchEntityException e) {
        iamClient.createUser(new CreateUserRequest(apkUser));
    }

    System.out.println("Requesting security credentials for " + apkUser);

    CreateAccessKeyRequest apkAccessRequest = new CreateAccessKeyRequest();
    apkAccessRequest.setUserName(apkUser);

    CreateAccessKeyResult apkAccessResult = iamClient.createAccessKey(apkAccessRequest);
    accessKeys.put(apkUser, apkAccessResult.getAccessKey());

    System.out.println("Configuring security policies...");

    Configuration cfg = new Configuration();
    cfg.setClassForTemplateLoading(InstanceConfigurator.class, "/org/akvo/flow/templates");
    cfg.setObjectWrapper(new DefaultObjectWrapper());
    cfg.setDefaultEncoding("UTF-8");

    Map<String, Object> data = new HashMap<String, Object>();
    data.put("bucketName", bucketName);
    data.put("version", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
    data.put("accessKey", accessKeys);

    Template t1 = cfg.getTemplate("apk-s3-policy.ftl");
    StringWriter apkPolicy = new StringWriter();
    t1.process(data, apkPolicy);

    Template t2 = cfg.getTemplate("gae-s3-policy.ftl");
    StringWriter gaePolicy = new StringWriter();
    t2.process(data, gaePolicy);

    iamClient.putUserPolicy(
            new PutUserPolicyRequest(apkUser, apkUser, Policy.fromJson(apkPolicy.toString()).toJson()));

    iamClient.putUserPolicy(
            new PutUserPolicyRequest(gaeUser, gaeUser, Policy.fromJson(gaePolicy.toString()).toJson()));

    System.out.println("Creating configuration files...");

    // survey.properties
    Map<String, Object> apkData = new HashMap<String, Object>();
    apkData.put("awsBucket", bucketName);
    apkData.put("awsAccessKeyId", accessKeys.get(apkUser).getAccessKeyId());
    apkData.put("awsSecretKey", accessKeys.get(apkUser).getSecretAccessKey());
    apkData.put("serverBase", "https://" + gaeId + ".appspot.com");
    apkData.put("restApiKey", apiKey);

    Template t3 = cfg.getTemplate("survey.properties.ftl");
    FileWriter fw = new FileWriter(new File(out, "/survey.properties"));
    t3.process(apkData, fw);

    // appengine-web.xml
    Map<String, Object> webData = new HashMap<String, Object>();
    webData.put("awsBucket", bucketName);
    webData.put("awsAccessKeyId", accessKeys.get(gaeUser).getAccessKeyId());
    webData.put("awsSecretAccessKey", accessKeys.get(gaeUser).getSecretAccessKey());
    webData.put("s3url", "https://" + bucketName + ".s3.amazonaws.com");
    webData.put("instanceId", gaeId);
    webData.put("alias", alias);
    webData.put("flowServices", flowServices);
    webData.put("apiKey", apiKey);
    webData.put("emailFrom", emailFrom);
    webData.put("emailTo", emailTo);
    webData.put("organization", orgName);
    webData.put("signingKey", signingKey);

    Template t5 = cfg.getTemplate("appengine-web.xml.ftl");
    FileWriter fw3 = new FileWriter(new File(out, "/appengine-web.xml"));
    t5.process(webData, fw3);

    System.out.println("Done");
}

From source file:org.applicationMigrator.userManagement.UserManagementWorker.java

License:Apache License

private void createUser(String ANDROID_ID) throws FileNotFoundException, IllegalArgumentException, IOException {
    Random randomizer = new Random(System.currentTimeMillis());
    String userName = "User" + randomizer.nextDouble();
    CreateUserRequest user = new CreateUserRequest();
    user.setUserName(userName);/*  w w w  .  ja v  a  2s  .  com*/
    AWSCredentials credentials = new PropertiesCredentials(
            new File("C:\\AndroidMigration\\Credentials\\AwsCredentials.properties"));
    AmazonIdentityManagementClient client = new AmazonIdentityManagementClient(credentials);
    CreateUserResult result = null;
    AccessKey accessKey = null;
    try {

        boolean userCreatedSuccessfully = false;
        while (!userCreatedSuccessfully) {
            try {
                result = client.createUser(user);
                userCreatedSuccessfully = true;
            } catch (EntityAlreadyExistsException exception) {
                user.setUserName(userName + randomizer.nextDouble());
                userCreatedSuccessfully = false;
            }
        }

        CreateAccessKeyRequest accessKeyRequest = new CreateAccessKeyRequest();
        accessKeyRequest.setUserName(result.getUser().getUserName());
        CreateAccessKeyResult accessKeyResult = client.createAccessKey(accessKeyRequest);
        accessKey = accessKeyResult.getAccessKey();

        grantPermissions(user, client);

        File userList = new File(USER_LIST_FILEPATH);
        BufferedWriter userListFileWriter = new BufferedWriter(new FileWriter(userList));

        // Concurrency ?
        userListFileWriter.write(ANDROID_ID + " ");
        userListFileWriter.write(accessKey.getAccessKeyId() + " ");
        userListFileWriter.write(accessKey.getSecretAccessKey() + " ");
        userListFileWriter.write(user.getUserName() + " ");
        userListFileWriter.close();
    } catch (Exception e) {
        if (accessKey != null) {
            DeleteAccessKeyRequest deleteAccessKeyRequest = new DeleteAccessKeyRequest(
                    accessKey.getAccessKeyId());
            deleteAccessKeyRequest.setUserName(user.getUserName());
            client.deleteAccessKey(deleteAccessKeyRequest);
            DeleteUserRequest deleteUserRequest = new DeleteUserRequest(user.getUserName());

            client.deleteUser(deleteUserRequest);
        }
        throw e;
    }
}