Returns the default Configuration provisioned for the specified AMS account and token provider.
@param apiServer the AMS account uri
@param azureAdTokenProvider the token provider
@return a Configuration
358679
public static Configuration configureWithAzureAdTokenProvider(
            URI apiServer,
            TokenProvider azureAdTokenProvider) {

        return configureWithAzureAdTokenProvider(Configuration.getInstance(), apiServer, azureAdTokenProvider);
    }
1192523
SamlIdentityProviderConfig build(CredentialResolverAdapter credentialResolver) {
        checkState(entityId != null, "entity ID of the identity provider is not set");

        // Use the entityId as a default key name.
        final Credential signing = credentialResolver.apply(firstNonNull(signingKey, entityId));
        final Credential encryption = credentialResolver.apply(firstNonNull(encryptionKey, entityId));

        return new SamlIdentityProviderConfig(entityId,
                                              signing,
                                              encryption,
                                              ssoEndpoint,
                                              sloReqEndpoint,
                                              sloResEndpoint,
                                              acsEndpoint,
                                              nameIdPolicy);
    }
1109037
def get_token_func():
        
        print("{}: token updater was triggered".format(datetime.datetime.now()))

        # in this example, the OAuth token is obtained using the ADAL library
        # however, the user can use any preferred method
        context = adal.AuthenticationContext(
            str.format("https://login.microsoftonline.com/{}", settings.ACTIVE_DIRECTORY_TENANT_ID),
            api_version=None, validate_authority=True)

        oauth_token = context.acquire_token_with_client_credentials(
            "https://storage.azure.com",
            settings.ACTIVE_DIRECTORY_APPLICATION_ID,
            settings.ACTIVE_DIRECTORY_APPLICATION_SECRET)

        # return the token itself and the interval to wait before this function should be called again
        # generally oauth_token['expiresIn'] - 180 is a good interval to give, as it tells the caller to
        # refresh the token 3 minutes before it expires, so here we are assuming that the token expiration
        # is at least longer than 3 minutes, the user should adjust it according to their AAD policy
        return oauth_token['accessToken'], oauth_token['expiresIn'] - 180
894022
public TokenAuthenticationManager getTokenAuthenticationManager() {
        if (tokenManager != null) {
            return tokenManager;
        }
        tokenManager = (TokenAuthenticationManager) ContainerManager.getComponent("tokenAuthenticationManager");
        return tokenManager;
    }
831398
public static CredentialsProvider newProxyCredentialsProvider
    (HttpClientSettings settings) {
        final CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(newAuthScope(settings), newNTCredentials(settings));
        return provider;
    }
153044
def GetDefaultToken(token):
  
  if token is None:
    token = default_token

  if not isinstance(token, access_control.ACLToken):
    raise access_control.UnauthorizedAccess(
        "Token is not properly specified. It should be an "
        "instance of grr.lib.access_control.ACLToken()")

  return token
597286
def get_default_config(self):
        
        config = super(RabbitMQCollector, self).get_default_config()
        config.update({
            'path': 'rabbitmq',
            'host': 'localhost:55672',
            'user': 'guest',
            'password': 'guest',
            'replace_dot': False,
            'replace_slash': False,
            'queues_ignored': '',
            'cluster': False,
            'scheme': 'http',
            'query_individual_queues': False,
        })
        return config
1258567
public SamlServiceProvider build() {

        // Must ensure that OpenSAML is initialized before building a SAML service provider.
        SamlInitializer.ensureAvailability();

        if (entityId == null) {
            throw new IllegalStateException("entity ID is not specified");
        }
        if (credentialResolver == null) {
            throw new IllegalStateException(CredentialResolver.class.getSimpleName() + " is not specified");
        }
        if (authorizer == null) {
            throw new IllegalStateException(Authorizer.class.getSimpleName() + " is not specified");
        }

        final Credential signingCredential = credentialResolver.apply(signingKey);
        if (signingCredential == null) {
            throw new IllegalStateException("cannot resolve a " + Credential.class.getSimpleName() +
                                            " for signing: " + signingKey);
        }
        final Credential encryptionCredential = credentialResolver.apply(encryptionKey);
        if (encryptionCredential == null) {
            throw new IllegalStateException("cannot resolve a " + Credential.class.getSimpleName() +
                                            " for encryption: " + encryptionKey);
        }
        validateSignatureAlgorithm(signatureAlgorithm, signingCredential);
        validateSignatureAlgorithm(signatureAlgorithm, encryptionCredential);

        // Initialize single logout service configurations.
        final List<SamlEndpoint> sloEndpoints;
        if (this.sloEndpoints.isEmpty()) {
            // Add two endpoints by default if there's no SLO endpoint specified by a user.
            sloEndpoints = ImmutableList.of(ofHttpPost("/saml/slo/post"),
                                            ofHttpRedirect("/saml/slo/redirect"));
        } else {
            sloEndpoints = ImmutableList.copyOf(this.sloEndpoints);
        }

        // Initialize assertion consumer service configurations.
        final List<SamlAssertionConsumerConfig> assertionConsumerConfigs;
        if (acsConfigBuilders.isEmpty()) {
            // Add two endpoints by default if there's no ACS endpoint specified by a user.
            assertionConsumerConfigs =
                    ImmutableList.of(new SamlAssertionConsumerConfigBuilder(this)
                                             .endpoint(ofHttpPost("/saml/acs/post")).asDefault(),
                                     new SamlAssertionConsumerConfigBuilder(this)
                                             .endpoint(ofHttpRedirect("/saml/acs/redirect")))
                                 .stream()
                                 .map(SamlAssertionConsumerConfigBuilder::build)
                                 .collect(toImmutableList());
        } else {
            // If there is only one ACS, it will be automatically a default ACS.
            if (acsConfigBuilders.size() == 1) {
                acsConfigBuilders.get(0).asDefault();
            }

            assertionConsumerConfigs = acsConfigBuilders.stream()
                                                        .map(SamlAssertionConsumerConfigBuilder::build)
                                                        .collect(toImmutableList());
        }

        // Collect assertion consumer service endpoints for checking duplication and existence.
        final Set<SamlEndpoint> acsEndpoints =
                assertionConsumerConfigs.stream().map(SamlAssertionConsumerConfig::endpoint)
                                        .collect(toImmutableSet());
        if (acsEndpoints.size() != assertionConsumerConfigs.size()) {
            throw new IllegalStateException("duplicated access consumer services exist");
        }

        // Initialize identity provider configurations.
        if (idpConfigBuilders.isEmpty()) {
            throw new IllegalStateException("no identity provider configuration is specified");
        }
        // If there is only one IdP, it will be automatically a default IdP.
        if (idpConfigBuilders.size() == 1) {
            idpConfigBuilders.get(0).asDefault();
        }

        final ImmutableMap.Builder<String, SamlIdentityProviderConfig> idpConfigs = ImmutableMap.builder();
        SamlIdentityProviderConfig defaultIdpConfig = null;
        for (final SamlIdentityProviderConfigBuilder builder : idpConfigBuilders) {
            if (builder.acsEndpoint() != null && !acsEndpoints.contains(builder.acsEndpoint())) {
                throw new IllegalStateException("unspecified access consumer service at " +
                                                builder.acsEndpoint());
            }

            final SamlIdentityProviderConfig config = builder.build(credentialResolver);

            validateSignatureAlgorithm(signatureAlgorithm, config.signingCredential());
            validateSignatureAlgorithm(signatureAlgorithm, config.encryptionCredential());

            idpConfigs.put(config.entityId(), config);

            if (builder.isDefault()) {
                if (defaultIdpConfig != null) {
                    throw new IllegalStateException("there has to be only one default identity provider");
                }
                defaultIdpConfig = config;
            }
        }

        if (idpConfigSelector == null) {
            if (defaultIdpConfig == null) {
                throw new IllegalStateException("default identity provider does not exist");
            }

            // Configure a default identity provider selector which always returns a default identity provider.
            final SamlIdentityProviderConfig defaultConfig = defaultIdpConfig;
            idpConfigSelector =
                    (unused1, unused2, unused3) -> CompletableFuture.completedFuture(defaultConfig);
        }

        // entityID would be used as a secret by default.
        try {
            requestIdManager = firstNonNull(requestIdManager,
                                            SamlRequestIdManager.ofJwt(entityId, entityId,
                                                                       60, 5));
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException("cannot create a " + SamlRequestIdManager.class.getSimpleName(),
                                            e);
        }

        return new SamlServiceProvider(authorizer,
                                       entityId,
                                       hostname,
                                       signingCredential,
                                       encryptionCredential,
                                       signatureAlgorithm,
                                       hostConfigBuilder.toAutoFiller(),
                                       metadataPath,
                                       idpConfigs.build(),
                                       defaultIdpConfig,
                                       idpConfigSelector,
                                       assertionConsumerConfigs,
                                       sloEndpoints,
                                       requestIdManager,
                                       ssoHandler,
                                       sloHandler);
    }
466087
@Autowired
    @Bean
    public WebSecurityConfigurerAdapter casConfigurationServerWebSecurityConfigurerAdapter(final ServerProperties serverProperties) {
        return new WebSecurityConfigurerAdapter() {
            @Override
            protected void configure(final HttpSecurity http) throws Exception {
                super.configure(http);
                val path = serverProperties.getServlet().getContextPath();
                http.authorizeRequests().antMatchers(path + "/decrypt/**").authenticated().and().csrf().disable();
                http.authorizeRequests().antMatchers(path + "/encrypt/**").authenticated().and().csrf().disable();
            }
        };
    }
378948
def _login_azure_app_token(client_id=None, client_secret=None, tenant_id=None):
        
        client_id = os.getenv('AZURE_CLIENT_ID') if not client_id else client_id
        client_secret = os.getenv('AZURE_CLIENT_SECRET') if not client_secret else client_secret
        tenant_id = os.getenv('AZURE_TENANT_ID') if not tenant_id else tenant_id
        credentials = ServicePrincipalCredentials(
            client_id=client_id,
            secret=client_secret,
            tenant=tenant_id,
        )
        return credentials
83844
private AWSKMSClient newAWSKMSClient(
            AWSCredentialsProvider credentialsProvider,
            ClientConfiguration clientConfig,
            CryptoConfiguration cryptoConfig,
            RequestMetricCollector requestMetricCollector
    ) {
        final AWSKMSClient kmsClient = new AWSKMSClient(
            credentialsProvider, clientConfig, requestMetricCollector);
        final Region kmsRegion = cryptoConfig.getAwsKmsRegion();
        if (kmsRegion != null)
            kmsClient.setRegion(kmsRegion);
        return kmsClient;
    }
1316330
def get_default_config(self):
        
        config = super(VMSFSCollector, self).get_default_config()
        config.update({
            'path':     'vmsfs'
        })
        return config
436542
public ServerAccessToken createAccessToken(AccessTokenRegistration reg)
		throws OAuthServiceException {
		ServerAccessToken token = new BearerAccessToken(reg.getClient(), 3600L);
		
		List<String> scope = reg.getApprovedScope().isEmpty() ? reg.getRequestedScope() 
				                                              : reg.getApprovedScope();
		token.setScopes(convertScopeToPermissions(reg.getClient(), scope));
		token.setSubject(reg.getSubject());
		token.setGrantType(reg.getGrantType());
		
		at = token;
		
		return token;
	}
1215377
public void setApiKeyPrefix(String apiKeyPrefix) {
        for (Authentication auth : authentications.values()) {
            if (auth instanceof ApiKeyAuth) {
                ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
                return;
            }
        }
        throw new RuntimeException("No API key authentication configured!");
    }
227398
private DefaultServiceDefaultsContext resolveServiceDefaults(ServiceDefaultsType serviceDefaults, RealmsContext realmsContext) {

        if (serviceDefaults == null) {
            return null;
        }

        DefaultAcceptOptionsContext acceptOptions = null;

        ServiceAcceptOptionsType serviceAcceptOptions = serviceDefaults.getAcceptOptions();
        if (serviceAcceptOptions != null) {
            acceptOptions = new DefaultAcceptOptionsContext(null, serviceAcceptOptions);
        }

        DefaultConnectOptionsContext connectOptions = null;
        ServiceConnectOptionsType serviceConnectOptions = serviceDefaults.getConnectOptions();
        if (serviceConnectOptions != null) {
            connectOptions = new DefaultConnectOptionsContext(null, serviceConnectOptions);
        }

        Map<String, String> mimeMappings = null;

        MimeMappingType[] mimeMappingTypes = serviceDefaults.getMimeMappingArray();
        if (mimeMappingTypes != null) {
            mimeMappings = new HashMap<>();
            for (MimeMappingType mmt : mimeMappingTypes) {
                mimeMappings.put(mmt.getExtension(), mmt.getMimeType());
            }
        }

        return new DefaultServiceDefaultsContext(acceptOptions, connectOptions, mimeMappings);
    }
637895
@VisibleForTesting
  public static int getConfImpl(Supplier<RetryHandlingMetaMasterConfigClient> clientSupplier,
      AlluxioConfiguration alluxioConf, String... args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd;
    try {
      cmd = parser.parse(OPTIONS, args, true /* stopAtNonOption */);
    } catch (ParseException e) {
      printHelp("Unable to parse input args: " + e.getMessage());
      return 1;
    }
    args = cmd.getArgs();

    Map<String, ConfigProperty> confMap = new HashMap<>();
    if (cmd.hasOption(MASTER_OPTION_NAME)) {
      // load cluster-wide configuration
      try (RetryHandlingMetaMasterConfigClient client = clientSupplier.get()) {
        client.getConfiguration().getClusterConf().forEach(
            prop -> confMap.put(prop.getName(), prop.toProto()));
      } catch (IOException e) {
        System.out.println("Unable to get master-side configuration: " + e.getMessage());
        return -1;
      }
    } else {
      // load local configuration
      for (PropertyKey key : alluxioConf.keySet()) {
        if (key.isBuiltIn()) {
          ConfigProperty.Builder config = ConfigProperty.newBuilder().setName(key.getName())
              .setSource(alluxioConf.getSource(key).toString());
          String val = alluxioConf.getOrDefault(key, null,
              ConfigurationValueOptions.defaults().useDisplayValue(true));
          if (val != null) {
            config.setValue(val);
          }
          confMap.put(key.getName(), config.build());
        }
      }
    }

    StringBuilder output = new StringBuilder();
    switch (args.length) {
      case 0:
        List<ConfigProperty> properties = new ArrayList<>(confMap.values());
        properties.sort(Comparator.comparing(ConfigProperty::getName));
        for (ConfigProperty property : properties) {
          String value = ConfigurationUtils.valueAsString(property.getValue());
          output.append(String.format("%s=%s", property.getName(), value));
          if (cmd.hasOption(SOURCE_OPTION_NAME)) {
            output.append(String.format(" (%s)", property.getSource()));
          }
          output.append("\n");
        }
        System.out.print(output.toString());
        break;
      case 1:
        if (!PropertyKey.isValid(args[0])) {
          printHelp(String.format("%s is not a valid configuration key", args[0]));
          return 1;
        }
        // args[0] can be the alias
        String key = PropertyKey.fromString(args[0]).getName();
        ConfigProperty property = confMap.get(key);
        if (property == null) {
          printHelp(String.format("%s is not found", key));
          return 1;
        }

        if (property.getValue() == null) {
          // value not set
          System.out.println("");
        } else {
          if (cmd.hasOption(SOURCE_OPTION_NAME)) {
            System.out.println(property.getSource());
          } else if (cmd.hasOption(UNIT_OPTION_NAME)) {
            String arg = cmd.getOptionValue(UNIT_OPTION_NAME).toUpperCase();
            try {
              ByteUnit byteUnit;
              byteUnit = ByteUnit.valueOf(arg);
              System.out.println(
                  FormatUtils.parseSpaceSize(property.getValue()) / byteUnit.getValue());
              break;
            } catch (Exception e) {
              // try next unit parse
            }
            try {
              TimeUnit timeUnit;
              timeUnit = TimeUnit.valueOf(arg);
              System.out.println(
                  FormatUtils.parseTimeSize(property.getValue()) / timeUnit.getValue());
              break;
            } catch (IllegalArgumentException ex) {
              // try next unit parse
            }
            printHelp(String.format("%s is not a valid unit", arg));
            return 1;
          } else {
            System.out.println(property.getValue());
          }
        }
        break;
      default:
        printHelp(String.format("More arguments than expected. Args: %s", Arrays.toString(args)));
        return 1;
    }
    return 0;
  }
749359
private static SslProvider defaultSslProvider() {
    if (OpenSsl.isAvailable()) {
      logger.log(Level.FINE, "Selecting OPENSSL");
      return SslProvider.OPENSSL;
    }
    Provider provider = findJdkProvider();
    if (provider != null) {
      logger.log(Level.FINE, "Selecting JDK with provider {0}", provider);
      return SslProvider.JDK;
    }
    logger.log(Level.INFO, "netty-tcnative unavailable (this may be normal)",
        OpenSsl.unavailabilityCause());
    logger.log(Level.INFO, "Conscrypt not found (this may be normal)");
    logger.log(Level.INFO, "Jetty ALPN unavailable (this may be normal)",
        JettyTlsUtil.getJettyAlpnUnavailabilityCause());
    throw new IllegalStateException(
        "Could not find TLS ALPN provider; "
        + "no working netty-tcnative, Conscrypt, or Jetty NPN/ALPN available");
  }