com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials Java Examples
The following examples show how to use
com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials.
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: GlobalKafkaConfiguration.java From remoting-kafka-plugin with MIT License | 6 votes |
private ListBoxModel fillCredentialsIdItems(@AncestorInPath Item item, @QueryParameter String credentialsId) { StandardListBoxModel result = new StandardListBoxModel(); if (item == null) { if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) { return result.includeCurrentValue(credentialsId); } } return result .includeMatchingAs( ACL.SYSTEM, Jenkins.get(), StandardUsernamePasswordCredentials.class, Collections.singletonList(KAFKA_SCHEME), CredentialsMatchers.always() ) .includeCurrentValue(credentialsId); }
Example #2
Source File: GerritApiBuilder.java From gerrit-code-review-plugin with Apache License 2.0 | 6 votes |
public GerritApiBuilder stepContext(StepContext context) throws URISyntaxException, IOException, InterruptedException { EnvVars envVars = context.get(EnvVars.class); logger(context.get(TaskListener.class).getLogger()); if (StringUtils.isNotEmpty(envVars.get("GERRIT_API_URL"))) { gerritApiUrl(envVars.get("GERRIT_API_URL")); } else if (StringUtils.isNotEmpty(envVars.get("GERRIT_CHANGE_URL"))) { gerritApiUrl(new GerritURI(new URIish(envVars.get("GERRIT_CHANGE_URL"))).getApiURI()); } insecureHttps(Boolean.parseBoolean(envVars.get("GERRIT_API_INSECURE_HTTPS"))); String credentialsId = StringUtils.defaultIfEmpty(envVars.get("GERRIT_CREDENTIALS_ID"), null); if (credentialsId != null) { credentials( CredentialsProvider.findCredentialById( credentialsId, StandardUsernamePasswordCredentials.class, context.get(Run.class))); } return this; }
Example #3
Source File: DockerSwarmComputerLauncher.java From docker-swarm-plugin with MIT License | 6 votes |
private void setAuthHeaders(DockerSwarmAgentTemplate dockerSwarmAgentTemplate, ServiceSpec crReq) { String credentialsId = dockerSwarmAgentTemplate.getPullCredentialsId(); // Exit if no credentials are provided if (credentialsId == null || credentialsId.length() == 0) { return; } // Get the credentials StandardUsernamePasswordCredentials credentials = CredentialsMatchers .firstOrNull(lookupCredentials(StandardUsernamePasswordCredentials.class, (Item) null, ACL.SYSTEM, Collections.<DomainRequirement>emptyList()), CredentialsMatchers.withId(credentialsId)); // Add the credentials to the header crReq.setAuthHeader(credentials.getUsername(), credentials.getPassword().getPlainText(), dockerSwarmAgentTemplate.getEmail(), dockerSwarmAgentTemplate.getServerAddress()); }
Example #4
Source File: CredentialsProviderImpl.java From git-client-plugin with MIT License | 6 votes |
/** * {@inheritDoc} * * If username/password is given, use it for HTTP auth. */ @Override public boolean supports(CredentialItem... items) { if (!(cred instanceof StandardUsernamePasswordCredentials)) return false; for (CredentialItem i : items) { if (i instanceof CredentialItem.Username) continue; else if (i instanceof CredentialItem.Password) continue; else return false; } return true; }
Example #5
Source File: AxivionSuite.java From warnings-ng-plugin with MIT License | 6 votes |
/** * Shows the user all available credential id items. * * @param item * jenkins configuration * @param credentialsId * current used credentials * * @return a list view of all credential ids */ public ListBoxModel doFillCredentialsIdItems( @AncestorInPath final Item item, @QueryParameter final String credentialsId) { StandardListBoxModel result = new StandardListBoxModel(); if (item == null) { if (!new JenkinsFacade().hasPermission(Jenkins.ADMINISTER)) { return result.includeCurrentValue(credentialsId); } } else { if (!item.hasPermission(Item.EXTENDED_READ) && !item.hasPermission(CredentialsProvider.USE_ITEM)) { return result.includeCurrentValue(credentialsId); } } return result.includeAs( ACL.SYSTEM, item, StandardUsernamePasswordCredentials.class, Collections.emptyList()) .includeCurrentValue(credentialsId); }
Example #6
Source File: GitLabPersonalAccessTokenCreator.java From gitlab-branch-source-plugin with MIT License | 6 votes |
@SuppressWarnings("unused") public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl, @QueryParameter String credentialsId) { Jenkins jenkins = Jenkins.get(); if (!jenkins.hasPermission(Jenkins.ADMINISTER)) { return new StandardListBoxModel().includeCurrentValue(credentialsId); } return new StandardUsernameListBoxModel() .includeEmptyValue() .includeMatchingAs( ACL.SYSTEM, jenkins, StandardUsernamePasswordCredentials.class, fromUri(defaultIfBlank(serverUrl, GitLabServer.GITLAB_SERVER_URL)).build(), CredentialsMatchers.always() ).includeMatchingAs( Jenkins.getAuthentication(), jenkins, StandardUsernamePasswordCredentials.class, fromUri(defaultIfBlank(serverUrl, GitLabServer.GITLAB_SERVER_URL)).build(), CredentialsMatchers.always() ); }
Example #7
Source File: GlobalKafkaConfiguration.java From remoting-kafka-plugin with MIT License | 6 votes |
@RequirePOST public ListBoxModel doFillKubernetesCredentialsIdItems() { Jenkins.get().checkPermission(Jenkins.ADMINISTER); return new StandardListBoxModel().withEmptySelection() .withMatching( CredentialsMatchers.anyOf( CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class), CredentialsMatchers.instanceOf(FileCredentials.class), CredentialsMatchers.instanceOf(TokenProducer.class), CredentialsMatchers.instanceOf(StandardCertificateCredentials.class), CredentialsMatchers.instanceOf(StringCredentials.class)), CredentialsProvider.lookupCredentials(StandardCredentials.class, Jenkins.get(), ACL.SYSTEM, Collections.EMPTY_LIST )); }
Example #8
Source File: GlobalKafkaConfiguration.java From remoting-kafka-plugin with MIT License | 6 votes |
private FormValidation checkCredentialsId(@AncestorInPath Item item, @QueryParameter String value) { if (item == null) { if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) { return FormValidation.ok(); } } if (value.startsWith("${") && value.endsWith("}")) { return FormValidation.warning("Cannot validate expression based credentials"); } if (CredentialsProvider.listCredentials( StandardUsernamePasswordCredentials.class, Jenkins.get(), ACL.SYSTEM, Collections.singletonList(KAFKA_SCHEME), CredentialsMatchers.withId(value) ).isEmpty()) { return FormValidation.error("Cannot find currently selected credentials"); } return FormValidation.ok(); }
Example #9
Source File: KafkaKubernetesCloud.java From remoting-kafka-plugin with MIT License | 6 votes |
@RequirePOST public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl) { Jenkins.get().checkPermission(Jenkins.ADMINISTER); return new StandardListBoxModel().withEmptySelection() .withMatching( CredentialsMatchers.anyOf( CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class), CredentialsMatchers.instanceOf(FileCredentials.class), CredentialsMatchers.instanceOf(TokenProducer.class), CredentialsMatchers.instanceOf(StandardCertificateCredentials.class), CredentialsMatchers.instanceOf(StringCredentials.class)), CredentialsProvider.lookupCredentials(StandardCredentials.class, Jenkins.get(), ACL.SYSTEM, serverUrl != null ? URIRequirementBuilder.fromUri(serverUrl).build() : Collections.EMPTY_LIST )); }
Example #10
Source File: SSHCredentialsTest.java From configuration-as-code-plugin with MIT License | 6 votes |
@Test @ConfiguredWithCode("SSHCredentialsTest.yml") @Issue("SECURITY-1279") public void shouldNotExportOrLogCredentials() throws Exception { StandardUsernamePasswordCredentials creds = getCredentials(StandardUsernamePasswordCredentials.class); assertEquals(CREDENTIALS_PASSWORD, creds.getPassword().getPlainText()); assertNotInLog(logging, CREDENTIALS_PASSWORD); BasicSSHUserPrivateKey certKey = getCredentials(BasicSSHUserPrivateKey.class); // JENKINS-50181 made getPrivateKey always append a trailing newline. assertEquals(PRIVATE_KEY + "\n", certKey.getPrivateKey()); assertNotInLog(logging, PRIVATE_KEY); // Verify that the password does not get exported String exportedConfig = j.exportToString(false); assertThat("There should be no password in the exported YAML", exportedConfig, not(containsString(CREDENTIALS_PASSWORD))); assertThat("There should be no private key in the exported YAML", exportedConfig, not(containsString(PRIVATE_KEY))); }
Example #11
Source File: CredentialsTest.java From configuration-as-code-plugin with MIT License | 6 votes |
@ConfiguredWithCode("GlobalCredentials.yml") @Test public void testGlobalScopedCredentials() { List<StandardUsernamePasswordCredentials> creds = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class,Jenkins.getInstanceOrNull(), null, Collections.emptyList()); assertThat(creds.size(), is(1)); assertEquals("user1", creds.get(0).getId()); assertEquals("Administrator", creds.get(0).getUsername()); assertEquals("secretPassword", creds.get(0).getPassword().getPlainText()); List<BasicSSHUserPrivateKey> creds2 = CredentialsProvider.lookupCredentials(BasicSSHUserPrivateKey.class,Jenkins.getInstanceOrNull(), null, Collections.emptyList()); assertThat(creds2.size(), is(1)); BasicSSHUserPrivateKey basicSSHUserPrivateKey = creds2.get(0); assertEquals("agentuser", basicSSHUserPrivateKey.getUsername()); assertEquals("password", basicSSHUserPrivateKey.getPassphrase().getPlainText()); assertEquals("ssh private key used to connect ssh slaves", basicSSHUserPrivateKey.getDescription()); assertThat(basicSSHUserPrivateKey.getPrivateKeySource().getPrivateKeys().size(), is(1)); String directKey = basicSSHUserPrivateKey.getPrivateKeySource().getPrivateKeys().get(0); assertThat(directKey, is("sp0ds9d+skkfjf")); }
Example #12
Source File: CredentialsHelper.java From violation-comments-to-github-plugin with MIT License | 6 votes |
@SuppressFBWarnings("NP_NULL_PARAM_DEREF") public static ListBoxModel doFillCredentialsIdItems( final Item item, final String credentialsId, final String uri) { final StandardListBoxModel result = new StandardListBoxModel(); if (item == null) { if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) { return result.includeCurrentValue(credentialsId); } } else { if (!item.hasPermission(Item.EXTENDED_READ) && !item.hasPermission(CredentialsProvider.USE_ITEM)) { return result.includeCurrentValue(credentialsId); } } return result // .includeEmptyValue() // .includeMatchingAs( item instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) item) : ACL.SYSTEM, item, StandardCredentials.class, URIRequirementBuilder.fromUri(uri).build(), CredentialsMatchers.anyOf( CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class), CredentialsMatchers.instanceOf(StringCredentials.class))) .includeCurrentValue(credentialsId); }
Example #13
Source File: CredentialsHelper.java From violation-comments-to-github-plugin with MIT License | 6 votes |
public static Optional<StandardCredentials> findCredentials( final Item item, final String credentialsId, final String uri) { if (isNullOrEmpty(credentialsId)) { return absent(); } return fromNullable( CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentials( StandardCredentials.class, item, item instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) item) : ACL.SYSTEM, URIRequirementBuilder.fromUri(uri).build()), CredentialsMatchers.allOf( CredentialsMatchers.withId(credentialsId), CredentialsMatchers.anyOf( CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class), CredentialsMatchers.instanceOf(StringCredentials.class))))); }
Example #14
Source File: BindingStepTest.java From credentials-binding-plugin with MIT License | 6 votes |
@Test public void incorrectType() throws Exception { story.addStep(new Statement() { @Override public void evaluate() throws Throwable { StringCredentialsImpl c = new StringCredentialsImpl(CredentialsScope.GLOBAL, "creds", "sample", Secret.fromString("s3cr3t")); CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), c); WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p"); p.setDefinition(new CpsFlowDefinition("" + "node {\n" + " withCredentials([usernamePassword(usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD', credentialsId: 'creds')]) {\n" + " }\n" + "}", true)); WorkflowRun r = story.j.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get()); // make sure error message contains information about the actual type and the expected type story.j.assertLogNotContains("s3cr3t", r); story.j.assertLogContains(StandardUsernamePasswordCredentials.class.getName(), r); // no descriptor for the interface type story.j.assertLogContains(stringCredentialsDescriptor.getDisplayName(), r); story.j.assertLogNotContains("\tat ", r); } }); }
Example #15
Source File: AbstractBitbucketScm.java From blueocean-plugin with MIT License | 6 votes |
/** * Validate that the credential is valid for the specified apiUrl. * Will throw a 401 ServiceException if the credential is invalid. * @param apiUrl * @param credential */ private void validateCredential(String apiUrl, StandardUsernamePasswordCredentials credential) { try { BitbucketApi api = getApi(apiUrl, this.getId(), credential); api.getUser(); //if credentials are wrong, this call will fail with 401 error } catch (ServiceException ex) { if (ex.status == 401) { throw new ServiceException.UnauthorizedException( new ErrorMessage(401, "Invalid username / password") ); } else { throw ex; } } }
Example #16
Source File: AbstractBitbucketScm.java From blueocean-plugin with MIT License | 6 votes |
/** * Validate that the existing credential is valid (if it exists). * Will throw a 401 ServiceException if the credential is invalid. * @param apiUrl */ private void validateExistingCredential(@Nonnull String apiUrl) { StandardUsernamePasswordCredentials bbCredentials = CredentialsUtils.findCredential(createCredentialId(apiUrl), StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement()); if (bbCredentials != null) { try { validateCredential(apiUrl, bbCredentials); } catch (ServiceException ex) { if (ex.status == 401) { throw new ServiceException.UnauthorizedException( new ErrorMessage(401, "Existing credential failed authorization") ); } else { throw ex; } } } }
Example #17
Source File: Connector.java From github-branch-source-plugin with MIT License | 6 votes |
public static void checkApiUrlValidity(@Nonnull GitHub gitHub, @CheckForNull StandardCredentials credentials) throws IOException { String hash; if (credentials == null) { hash = "anonymous"; } else if (credentials instanceof StandardUsernamePasswordCredentials) { StandardUsernamePasswordCredentials c = (StandardUsernamePasswordCredentials) credentials; hash = Util.getDigestOf(c.getPassword().getPlainText() + SALT); } else { // TODO OAuth support throw new IOException("Unsupported credential type: " + credentials.getClass().getName()); } String key = gitHub.getApiUrl() + "::" + hash; synchronized (apiUrlValid) { Long last = apiUrlValid.get(key); if (last != null && last > System.currentTimeMillis() - API_URL_REVALIDATE_MILLIS) { return; } gitHub.checkApiUrlValidity(); apiUrlValid.put(key, System.currentTimeMillis()); } }
Example #18
Source File: GitReadSaveService.java From blueocean-plugin with MIT License | 6 votes |
@Nonnull protected StandardUsernamePasswordCredentials getCredentialForUser(@Nonnull Item item, @Nonnull String repositoryUrl) { User user = User.current(); if (user == null) { //ensure this session has authenticated user throw new ServiceException.UnauthorizedException("No logged in user found"); } String credentialId = GitScm.makeCredentialId(repositoryUrl); StandardUsernamePasswordCredentials credential = null; if (credentialId != null) { credential = CredentialsUtils.findCredential(credentialId, StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement()); } if (credential == null) { throw new ServiceException.UnauthorizedException("No credential found for " + credentialId + " for user " + user.getDisplayName()); } return credential; }
Example #19
Source File: ContainerExecDecoratorPipelineTest.java From kubernetes-plugin with Apache License 2.0 | 6 votes |
@Test public void docker() throws Exception { StandardUsernamePasswordCredentials credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "ContainerExecDecoratorPipelineTest-docker", "bob", "myusername", "secret_password"); SystemCredentialsProvider.getInstance().getCredentials().add(credentials); containerExecLogs.capture(1000); assertNotNull(createJobThenScheduleRun()); r.waitForCompletion(b); // docker login will fail but we can check that it runs the correct command r.assertLogContains("Executing command: \"docker\" \"login\" \"-u\" \"myusername\" \"-p\" ******** \"https://index.docker.io/v1/\"", b); // check that we don't accidentally start exporting sensitive info to the build log r.assertLogNotContains("secret_password", b); // check that we don't accidentally start exporting sensitive info to the Jenkins log assertFalse("credential leaked to log", containerExecLogs.getMessages().stream().anyMatch(msg -> msg.contains("secret_password"))); }
Example #20
Source File: AnsibleAdHocCommandInvocationTest.java From ansible-plugin with Apache License 2.0 | 5 votes |
@Test @Ignore("Secret can neither be instanced nor mocked") public void should_handle_password_credentials() throws Exception { // Given Inventory inventory = new InventoryPath("/tmp/hosts"); StandardUsernamePasswordCredentials password = mock(StandardUsernamePasswordCredentials.class); when(password.getUsername()).thenReturn("mylogin"); when(password.getPassword()).thenReturn(Secret.fromString("aStrongSecretPassword")); BuildListener listener = mock(BuildListener.class); CLIRunner runner = mock(CLIRunner.class); AbstractBuild<?,?> build = mock(AbstractBuild.class); when(build.getEnvironment(any(TaskListener.class))).thenReturn(new EnvVars()); AnsibleAdHocCommandInvocation invocation = new AnsibleAdHocCommandInvocation("/usr/local/bin/ansible", build, listener); invocation.setHostPattern("localhost"); invocation.setInventory(inventory); invocation.setModule("ping"); invocation.setCredentials(password); invocation.setForks(5); // When invocation.execute(runner); // Then ArgumentCaptor<ArgumentListBuilder> argument = ArgumentCaptor.forClass(ArgumentListBuilder.class); verify(runner).execute(argument.capture(), anyMap()); assertThat(argument.getValue().toString()) .isEqualTo("sshpass ****** /usr/local/bin/ansible localhost -i /tmp/hosts -m ping -f 5 " + "-u" + " mylogin -k"); }
Example #21
Source File: SmartCredentialsProviderTest.java From git-client-plugin with MIT License | 5 votes |
@Test public void testClearCredentialsItem() { String expectedUsername = "expected-add-credentials-username"; String secretValue = "secret-value"; Secret secret = Secret.fromString(secretValue); StandardUsernamePasswordCredentials credentials = new StandardUsernamePasswordCredentialsImpl(expectedUsername, secret); maskedUsername.setValue(credentials); assertEquals(credentials, maskedUsername.getValue()); maskedUsername.clear(); assertNull(maskedUsername.getValue()); }
Example #22
Source File: GithubRepositoryContainer.java From blueocean-plugin with MIT License | 5 votes |
public GithubRepositoryContainer(Scm scm, String orgUrl, String orgId, String repoType, StandardUsernamePasswordCredentials credentials, Reachable parent) { this.rootUrl = scm.getUri(); this.self = parent.getLink().rel("repositories"); this.credentials = credentials; this.orgId = orgId; this.orgUrl = orgUrl; this.repoType = repoType; }
Example #23
Source File: GithubPipelineCreateRequest.java From blueocean-plugin with MIT License | 5 votes |
@Override protected List<ErrorMessage.Error> validate(String name, BlueScmConfig scmConfig) { List<ErrorMessage.Error> errors = Lists.newArrayList(); StandardUsernamePasswordCredentials credentials = null; String credentialId = computeCredentialIdWithGithubDefault(scmConfig); if(StringUtils.isBlank(scmConfig.getUri())){ errors.add(new ErrorMessage.Error("scmConfig.uri", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "uri is required")); } if(credentialId != null){ credentials = CredentialsUtils.findCredential(credentialId, StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement()); } if (credentials == null) { errors.add(new ErrorMessage.Error("scmConfig.credentialId", ErrorMessage.Error.ErrorCodes.NOT_FOUND.toString(), "No Credentials instance found for credentialId: " + credentialId)); }else if(StringUtils.isNotBlank(scmConfig.getUri())){ String accessToken = credentials.getPassword().getPlainText(); try { validateGithubAccessToken(accessToken, scmConfig.getUri()); } catch (IOException e) { throw new ServiceException.UnexpectedErrorException(e.getMessage()); } } if(StringUtils.isBlank((String)scmConfig.getConfig().get("repoOwner"))){ errors.add(new ErrorMessage.Error("scmConfig.repoOwner", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "repoOwner is required")); } if(StringUtils.isBlank((String)scmConfig.getConfig().get("repository"))){ errors.add(new ErrorMessage.Error("scmConfig.repository", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "repository is required")); } return errors; }
Example #24
Source File: SmartCredentialsProviderTest.java From git-client-plugin with MIT License | 5 votes |
@Test public void testGetThrowsException() { String expectedUsername = "expected-add-credentials-username"; Secret secret = Secret.fromString("password-secret"); StandardUsernamePasswordCredentials credentials = new StandardUsernamePasswordCredentialsImpl(expectedUsername, secret); provider.addCredentials(gitURI.toString(), credentials); assertThrows(UnsupportedCredentialItem.class, () -> { provider.get(gitURI, username, password, maskedUsername, unmaskedUsername, maskedStringType); }); }
Example #25
Source File: BitbucketPipelineCreateRequest.java From blueocean-plugin with MIT License | 5 votes |
@Override protected List<ErrorMessage.Error> validate(String name, BlueScmConfig scmConfig) { List<ErrorMessage.Error> errors = Lists.newArrayList(); StandardUsernamePasswordCredentials credentials = null; String credentialId = computeCredentialId(scmConfig); if(credentialId != null){ credentials = CredentialsUtils.findCredential(credentialId, StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement()); } if (credentials == null) { errors.add(new ErrorMessage.Error("scmConfig.credentialId", ErrorMessage.Error.ErrorCodes.NOT_FOUND.toString(), "No Credentials instance found for credentialId: " + credentialId)); } if(StringUtils.isBlank((String)scmConfig.getConfig().get("repoOwner"))){ errors.add(new ErrorMessage.Error("scmConfig.repoOwner", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "repoOwner is required")); } if(StringUtils.isBlank((String)scmConfig.getConfig().get("repository"))){ errors.add(new ErrorMessage.Error("scmConfig.repository", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "repository is required")); } if(StringUtils.isBlank(scmConfig.getUri())){ errors.add(new ErrorMessage.Error("scmConfig.uri", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "uri is required")); } return errors; }
Example #26
Source File: CredentialsHelper.java From git-changelog-plugin with MIT License | 5 votes |
public static Optional<StandardUsernamePasswordCredentials> findSecretUsernamePassword( String credentialsId) { Optional<StandardUsernamePasswordCredentials> token = Optional.empty(); if (!isNullOrEmpty(credentialsId)) { final Optional<StandardUsernamePasswordCredentials> credentials = CredentialsHelper.findUserCredentials(credentialsId); if (credentials.isPresent()) { checkNotNull(credentials.get(), "Credentials selected but not set!"); return credentials; } } return token; }
Example #27
Source File: WithAWSStep.java From pipeline-aws-plugin with Apache License 2.0 | 5 votes |
private void withCredentials(@Nonnull Run<?, ?> run, @Nonnull EnvVars localEnv) throws IOException, InterruptedException { if (!StringUtils.isNullOrEmpty(this.step.getCredentials())) { StandardUsernamePasswordCredentials usernamePasswordCredentials = CredentialsProvider.findCredentialById(this.step.getCredentials(), StandardUsernamePasswordCredentials.class, run, Collections.emptyList()); AmazonWebServicesCredentials amazonWebServicesCredentials = CredentialsProvider.findCredentialById(this.step.getCredentials(), AmazonWebServicesCredentials.class, run, Collections.emptyList()); if (usernamePasswordCredentials != null) { localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, usernamePasswordCredentials.getUsername()); localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, usernamePasswordCredentials.getPassword().getPlainText()); } else if (amazonWebServicesCredentials != null) { AWSCredentials awsCredentials; if (StringUtils.isNullOrEmpty(this.step.getIamMfaToken())) { this.getContext().get(TaskListener.class).getLogger().format("Constructing AWS Credentials"); awsCredentials = amazonWebServicesCredentials.getCredentials(); } else { // Since the getCredentials does its own roleAssumption, this is all it takes to get credentials // with this token. this.getContext().get(TaskListener.class).getLogger().format("Constructing AWS Credentials utilizing MFA Token"); awsCredentials = amazonWebServicesCredentials.getCredentials(this.step.getIamMfaToken()); BasicSessionCredentials basicSessionCredentials = (BasicSessionCredentials) awsCredentials; localEnv.override(AWSClientFactory.AWS_SESSION_TOKEN, basicSessionCredentials.getSessionToken()); } localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, awsCredentials.getAWSAccessKeyId()); localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, awsCredentials.getAWSSecretKey()); } else { throw new RuntimeException("Cannot find a Username with password credential with the ID " + this.step.getCredentials()); } } else if (!StringUtils.isNullOrEmpty(this.step.getSamlAssertion())) { localEnv.override(AWSClientFactory.AWS_ACCESS_KEY_ID, "access_key_not_used_will_pass_through_SAML_assertion"); localEnv.override(AWSClientFactory.AWS_SECRET_ACCESS_KEY, "secret_access_key_not_used_will_pass_through_SAML_assertion"); } this.envVars.overrideAll(localEnv); }
Example #28
Source File: BitbucketBuildStatusNotifier.java From bitbucket-build-status-notifier-plugin with MIT License | 5 votes |
private StandardUsernamePasswordCredentials getCredentials(AbstractBuild<?,?> build) { StandardUsernamePasswordCredentials credentials = BitbucketBuildStatusHelper .getCredentials(getCredentialsId(), build.getProject()); if (credentials == null) { credentials = BitbucketBuildStatusHelper .getCredentials(this.getDescriptor().getGlobalCredentialsId(), null); } return credentials; }
Example #29
Source File: AxivionSuite.java From warnings-ng-plugin with MIT License | 5 votes |
/** * Checks whether valid credentials are given. * * @param item * jenkins configuration * @param credentialsId * id of the stored credentials pair * * @return {@link FormValidation#ok()} if credentials exist and are valid */ public FormValidation doCheckCredentialsId( @AncestorInPath final Item item, @QueryParameter final String credentialsId) { if (StringUtils.isBlank(credentialsId)) { return FormValidation.error("You have to provide credentials."); } if (item == null) { if (!new JenkinsFacade().hasPermission(Jenkins.ADMINISTER)) { return FormValidation.ok(); } } else { if (!item.hasPermission(Item.EXTENDED_READ) && !item.hasPermission(CredentialsProvider.USE_ITEM)) { return FormValidation.ok(); } } if (CredentialsMatchers.firstOrNull( CredentialsProvider.lookupCredentials( StandardUsernamePasswordCredentials.class, item, ACL.SYSTEM, Collections.emptyList()), CredentialsMatchers.withId(credentialsId)) == null) { return FormValidation.error("Cannot find currently selected credentials."); } return FormValidation.ok(); }
Example #30
Source File: AbstractScmContentProvider.java From blueocean-plugin with MIT License | 5 votes |
private ScmGetRequest(@Nonnull String apiUrl, @Nonnull String owner, @Nonnull String repo, @Nullable String branch, @Nonnull String path, @Nullable String type, @Nonnull StandardUsernamePasswordCredentials credentials) { this.apiUrl = apiUrl; this.owner = owner; this.repo = repo; this.branch = branch; this.path = path; this.type = type; this.credentials = credentials; }