Java Code Examples for com.microsoft.azure.AzureEnvironment#AZURE

The following examples show how to use com.microsoft.azure.AzureEnvironment#AZURE . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AzureAuthHelper.java    From azure-gradle-plugins with MIT License 6 votes vote down vote up
protected AzureEnvironment getAzureEnvironment(String environment) {
    if (StringUtils.isEmpty(environment)) {
        return AzureEnvironment.AZURE;
    }

    switch (environment.toUpperCase(Locale.ENGLISH)) {
        case "AZURE_CHINA":
            return AzureEnvironment.AZURE_CHINA;
        case "AZURE_GERMANY":
            return AzureEnvironment.AZURE_GERMANY;
        case "AZURE_US_GOVERNMENT":
            return AzureEnvironment.AZURE_US_GOVERNMENT;
        default:
            return AzureEnvironment.AZURE;
    }
}
 
Example 2
Source File: AzureAuthHelper.java    From azure-gradle-plugins with MIT License 6 votes vote down vote up
private AzureEnvironment getAzureEnvironment(String environment) {
    if (StringUtils.isEmpty(environment)) {
        return AzureEnvironment.AZURE;
    }

    switch (environment.toUpperCase(Locale.ENGLISH)) {
        case "AZURE_CHINA":
            return AzureEnvironment.AZURE_CHINA;
        case "AZURE_GERMANY":
            return AzureEnvironment.AZURE_GERMANY;
        case "AZURE_US_GOVERNMENT":
            return AzureEnvironment.AZURE_US_GOVERNMENT;
        default:
            return AzureEnvironment.AZURE;
    }
}
 
Example 3
Source File: Utils.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Get the Azure storage account connection string.
 * @param accountName storage account name
 * @param accountKey storage account key
 * @param restClient rest client
 * @return the storage account connection string.
 */
public static String getStorageConnectionString(String accountName, String accountKey,
                                                RestClient restClient) {
    AzureEnvironment environment = AzureEnvironment.AZURE;
    if (restClient != null) {
        try {
            AzureEnvironment environment1 = extractAzureEnvironment(restClient);
            if (environment1 != null && environment1.storageEndpointSuffix() != null) {
                environment = environment1;
            }
        } catch (IllegalArgumentException e) {
            // ignored
        }
    }
    String suffix = environment.storageEndpointSuffix().replaceAll("^\\.*", "");
    return String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s;EndpointSuffix=%s",
            accountName, accountKey, suffix);
}
 
Example 4
Source File: AzureCredentialConnector.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> initCodeGrantFlow(CloudContext cloudContext, CloudCredential cloudCredential) {
    Map<String, String> parameters = new HashMap<>();
    AzureCredentialView azureCredential = new AzureCredentialView(cloudCredential);

    ApplicationTokenCredentials applicationCredentials = new ApplicationTokenCredentials(
            azureCredential.getAccessKey(),
            azureCredential.getTenantId(),
            azureCredential.getSecretKey(),
            AzureEnvironment.AZURE);

    String replyUrl = appCreationCommand.getRedirectURL(String.valueOf(cloudContext.getAccountId()), azureCredential.getDeploymentAddress());
    CbDelegatedTokenCredentials creds = new CbDelegatedTokenCredentials(applicationCredentials, replyUrl, authenticationContextProvider,
            cbRefreshTokenClientProvider);

    String state = UUID.randomUUID().toString();
    parameters.put("appLoginUrl", creds.generateAuthenticationUrl(state));
    parameters.put("appReplyUrl", replyUrl);
    parameters.put("codeGrantFlowState", state);
    return parameters;
}
 
Example 5
Source File: AzureAccount.java    From clouditor with Apache License 2.0 5 votes vote down vote up
public AzureTokenCredentials resolveCredentials() throws IOException {
  if (this.isAutoDiscovered()) {
    return AzureAccount.defaultCredentialProviderChain();
  } else {
    return new ApplicationTokenCredentials(
        clientId, tenantId, clientSecret, AzureEnvironment.AZURE);
  }
}
 
Example 6
Source File: AzureCredentialManager.java    From pacbot with Apache License 2.0 5 votes vote down vote up
private static ApplicationTokenCredentials getCredentials(){
	String clientId = System.getProperty("azure.clientId");
	String domain = System.getProperty("azure.domain");
	String secret = System.getProperty("azure.secret");
	return new ApplicationTokenCredentials(clientId, 
			domain, secret, AzureEnvironment.AZURE);
}
 
Example 7
Source File: AzureCredentialProvider.java    From pacbot with Apache License 2.0 5 votes vote down vote up
private  ApplicationTokenCredentials getCredentials(String tenant){
	Map<String,String> creds = decodeCredetials().get(tenant);
	String clientId = creds.get("clientId");
	String secret = creds.get("secretId");
	return new ApplicationTokenCredentials(clientId, 
			tenant, secret, AzureEnvironment.AZURE);
}
 
Example 8
Source File: AzureKeyVaultStore.java    From data-transfer-project with Apache License 2.0 5 votes vote down vote up
public AzureKeyVaultStore(
    String keyVaultName, String tenantId, String clientId, String clientSecret) {
  vaultUrl = String.format(VAULT_ADDRESS, keyVaultName);

  ApplicationTokenCredentials credentials =
      new ApplicationTokenCredentials(clientId, tenantId, clientSecret, AzureEnvironment.AZURE);
  vaultClient = new KeyVaultClient(credentials);
}
 
Example 9
Source File: AzureCliSubscription.java    From autorest-clientruntime-for-java with MIT License 5 votes vote down vote up
AzureEnvironment environment() {
    if (environmentName == null) {
        return null;
    } else if (environmentName.equalsIgnoreCase("AzureCloud")) {
        return AzureEnvironment.AZURE;
    } else if (environmentName.equalsIgnoreCase("AzureChinaCloud")) {
        return AzureEnvironment.AZURE_CHINA;
    } else if (environmentName.equalsIgnoreCase("AzureGermanCloud")) {
        return AzureEnvironment.AZURE_GERMANY;
    } else if (environmentName.equalsIgnoreCase("AzureUSGovernment")) {
        return AzureEnvironment.AZURE_US_GOVERNMENT;
    } else {
        return null;
    }
}
 
Example 10
Source File: AzureSetup.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private void validateAdlsFileSystem(CloudCredential credential, SpiFileSystem fileSystem) {
    Map<String, Object> credentialAttributes = credential.getParameters();
    CloudAdlsView cloudFileSystem = (CloudAdlsView) fileSystem.getCloudFileSystems().get(0);
    String clientSecret = String.valueOf(credentialAttributes.get(CloudAdlsView.CREDENTIAL_SECRET_KEY));
    String subscriptionId = String.valueOf(credentialAttributes.get(CloudAdlsView.SUBSCRIPTION_ID));
    String clientId = String.valueOf(credentialAttributes.get(CloudAdlsView.ACCESS_KEY));
    String tenantId = StringUtils.isEmpty(cloudFileSystem.getTenantId()) ? credential.getStringParameter(TENANT_ID) : cloudFileSystem.getTenantId();
    String accountName = cloudFileSystem.getAccountName();

    ApplicationTokenCredentials creds = new ApplicationTokenCredentials(clientId, tenantId, clientSecret, AzureEnvironment.AZURE);
    DataLakeStoreAccountManagementClient adlsClient = new DataLakeStoreAccountManagementClientImpl(creds);
    adlsClient.withSubscriptionId(subscriptionId);
    PagedList<DataLakeStoreAccountBasic> dataLakeStoreAccountPagedList = adlsClient.accounts().list();
    boolean validAccountname = false;

    List<DataLakeStoreAccountBasic> dataLakeStoreAccountList = new ArrayList<>();
    while (dataLakeStoreAccountPagedList.hasNextPage()) {
        dataLakeStoreAccountList.addAll(dataLakeStoreAccountPagedList);
        dataLakeStoreAccountPagedList.loadNextPage();
    }

    for (DataLakeStoreAccountBasic account : dataLakeStoreAccountList) {
        if (account.name().equalsIgnoreCase(accountName)) {
            validAccountname = true;
            break;
        }
    }
    if (!validAccountname) {
        throw new CloudConnectorException("The provided file system account name does not belong to a valid ADLS account");
    }
}
 
Example 11
Source File: AzureClientCredentials.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private AzureTokenCredentials getAzureCredentials() {
    String tenantId = credentialView.getTenantId();
    String clientId = credentialView.getAccessKey();
    String secretKey = credentialView.getSecretKey();
    String subscriptionId = credentialView.getSubscriptionId();
    AzureEnvironment azureEnvironment = AzureEnvironment.AZURE;
    ApplicationTokenCredentials applicationTokenCredentials = new ApplicationTokenCredentials(clientId, tenantId, secretKey, azureEnvironment);
    Optional<Boolean> codeGrantFlow = Optional.ofNullable(credentialView.codeGrantFlow());

    AzureTokenCredentials result = applicationTokenCredentials;
    if (codeGrantFlow.orElse(Boolean.FALSE)) {
        String refreshToken = credentialView.getRefreshToken();
        if (StringUtils.isNotEmpty(refreshToken)) {
            LOGGER.info("Creating Azure credentials for a new delegated token with refresh token, credential: {}", credentialView.getName());
            String resource = azureEnvironment.managementEndpoint();
            CBRefreshTokenClient refreshTokenClient = cbRefreshTokenClientProvider.getCBRefreshTokenClient(azureEnvironment.activeDirectoryEndpoint());
            AuthenticationResult authenticationResult = refreshTokenClient.refreshToken(tenantId, clientId, secretKey, resource, refreshToken, false);

            if (authenticationResult == null) {
                String msg = String.format("New token couldn't be obtain with refresh token for credential: %s", credentialView.getName());
                LOGGER.warn(msg);
                throw new CloudConnectorException(msg);
            }

            Map<String, AuthenticationResult> tokens = Map.of(resource, authenticationResult);
            result = new CbDelegatedTokenCredentials(applicationTokenCredentials, resource, tokens, secretKey, authenticationContextProvider,
                    cbRefreshTokenClientProvider);
        } else {
            LOGGER.info("Creating Azure credentials for a new delegated token with authorization code, credential: {}", credentialView.getName());
            String appReplyUrl = credentialView.getAppReplyUrl();
            String authorizationCode = credentialView.getAuthorizationCode();
            result = new CbDelegatedTokenCredentials(applicationTokenCredentials, appReplyUrl, authorizationCode, secretKey, authenticationContextProvider,
                    cbRefreshTokenClientProvider);
        }
    } else {
        LOGGER.info("Creating Azure credentials with application token credentials, credential: {}", credentialView.getName());
    }
    return result.withDefaultSubscriptionId(subscriptionId);
}
 
Example 12
Source File: AzureClientConfiguration.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Bean
public Azure getAzure() {
        Credential credential = azureProperties.getCredential();
        AzureTokenCredentials azureTokenCredentials =
                new ApplicationTokenCredentials(credential.getAppId(), credential.getTenantId(), credential.getAppPassword(), AzureEnvironment.AZURE);
        return Azure
                .configure()
                .withProxyAuthenticator(new JavaNetAuthenticator())
                .withLogLevel(LogLevel.BODY_AND_HEADERS)
                .authenticate(azureTokenCredentials)
                .withSubscription(credential.getSubscriptionId());
}
 
Example 13
Source File: ManageVirtualMachineFromMSIEnabledVirtualMachine.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
/**
 * Main entry point.
 *
 * @param args the parameters
 */
public static void main(String[] args) {
    try {
        final Region region = Region.US_WEST_CENTRAL;

        // This sample required to be run from a MSI (User Assigned or System Assigned) enabled virtual machine with role
        // based contributor access to the resource group specified as the second command line argument.
        //
        // see https://github.com/Azure-Samples/compute-java-manage-user-assigned-msi-enabled-virtual-machine.git
        //

        final String usage = "Usage: mvn clean compile exec:java -Dexec.args=\"<subscription-id> <rg-name> [<client-id>]\"";
        if (args.length < 2) {
            throw new IllegalArgumentException(usage);
        }

        final String subscriptionId = args[0];
        final String resourceGroupName = args[1];
        final String clientId = args.length > 2 ? args[2] : null;
        final String linuxVMName = Utils.createRandomName("VM1");
        final String userName = "tirekicker";
        // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")]
        final String password = "12NewPA$$w0rd!";

        //=============================================================
        // MSI Authenticate

        MSICredentials credentials = new MSICredentials(AzureEnvironment.AZURE);
        if (clientId != null) {
            // If User Assigned MSI client id is specified then switch to "User Assigned MSI" auth mode
            //
            credentials = credentials.withClientId(clientId);
        }

        Azure azure = Azure.configure()
                .withLogLevel(LogLevel.BODY_AND_HEADERS)
                .authenticate(credentials)
                .withSubscription(subscriptionId);

        // Print selected subscription
        System.out.println("Selected subscription: " + azure.subscriptionId());

        //=============================================================
        // Create a Linux VM using MSI credentials

        System.out.println("Creating a Linux VM using MSI credentials");

        VirtualMachine virtualMachine = azure.virtualMachines()
                .define(linuxVMName)
                .withRegion(region)
                .withExistingResourceGroup(resourceGroupName)
                .withNewPrimaryNetwork("10.0.0.0/28")
                .withPrimaryPrivateIPAddressDynamic()
                .withoutPrimaryPublicIPAddress()
                .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
                .withRootUsername(userName)
                .withRootPassword(password)
                .withSize(VirtualMachineSizeTypes.STANDARD_DS2_V2)
                .create();

        System.out.println("Created virtual machine using MSI credentials");
        Utils.print(virtualMachine);

    } catch (Exception e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}
 
Example 14
Source File: MockUserTokenCredentials.java    From azure-keyvault-java with MIT License 4 votes vote down vote up
public MockUserTokenCredentials() {
    this("","","","", AzureEnvironment.AZURE);
}
 
Example 15
Source File: MSICredentials.java    From autorest-clientruntime-for-java with MIT License 4 votes vote down vote up
/**
 * Initializes a new instance of the MSICredentials.
 */
public MSICredentials() {
    this(AzureEnvironment.AZURE);
}
 
Example 16
Source File: AzureTokenCredentials.java    From autorest-clientruntime-for-java with MIT License 2 votes vote down vote up
/**
 * Initializes a new instance of the AzureTokenCredentials.
 *
 * @param environment the Azure environment to use
 * @param domain the tenant or domain the credential is authorized to
 */
public AzureTokenCredentials(AzureEnvironment environment, String domain) {
    super("Bearer", null);
    this.environment = (environment == null) ? AzureEnvironment.AZURE : environment;
    this.domain = domain;
}