Search in sources :

Example 21 with PasswordEncoder

use of org.springframework.security.crypto.password.PasswordEncoder in project cas by apereo.

the class QueryAndEncodeDatabaseAuthenticationHandlerTests method verifyAuthenticationSuccessfulWithAPasswordEncoder.

@Test
public void verifyAuthenticationSuccessfulWithAPasswordEncoder() throws Exception {
    val properties = new QueryEncodeJdbcAuthenticationProperties().setAlgorithmName(ALG_NAME).setSql(buildSql()).setPasswordFieldName(PASSWORD_FIELD_NAME).setNumberOfIterationsFieldName(NUM_ITERATIONS_FIELD_NAME).setStaticSalt(STATIC_SALT).setSaltFieldName("salt");
    val q = new QueryAndEncodeDatabaseAuthenticationHandler(properties, null, PrincipalFactoryUtils.newPrincipalFactory(), dataSource);
    q.setPasswordEncoder(new PasswordEncoder() {

        @Override
        public String encode(final CharSequence password) {
            return password.toString().concat("1");
        }

        @Override
        public boolean matches(final CharSequence rawPassword, final String encodedPassword) {
            return true;
        }
    });
    q.setPrincipalNameTransformer(new PrefixSuffixPrincipalNameTransformer("user", null));
    val r = q.authenticate(CoreAuthenticationTestUtils.getCredentialsWithDifferentUsernameAndPassword("1", "user"));
    assertNotNull(r);
    assertEquals("user1", r.getPrincipal().getId());
}
Also used : lombok.val(lombok.val) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) QueryEncodeJdbcAuthenticationProperties(org.apereo.cas.configuration.model.support.jdbc.authn.QueryEncodeJdbcAuthenticationProperties) PrefixSuffixPrincipalNameTransformer(org.apereo.cas.util.transforms.PrefixSuffixPrincipalNameTransformer) Test(org.junit.jupiter.api.Test)

Example 22 with PasswordEncoder

use of org.springframework.security.crypto.password.PasswordEncoder in project vft-capture by videofirst.

the class SecurityUtils method checkCreatePassword.

/**
 * Create password if first command arg is `-pwd`.
 */
public static void checkCreatePassword(String[] args) {
    // Check to see if we're trying to change password
    if ((args.length == 1 || args.length == 2) && "-pwd".equals(args[0])) {
        System.out.println("=============================");
        System.out.println("VF CAPTURE - PASSWORD ENCODER");
        System.out.println("=============================");
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(SecurityConfiguration.BCRYPT_STRENGTH);
        if (args.length == 2) {
            System.out.println("\nEncoded output [ " + passwordEncoder.encode(args[1]) + " ]\n");
            System.exit(0);
        }
        while (true) {
            try {
                System.out.print("\nPlease enter password (or q to exit): - ");
                System.out.flush();
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                String input = br.readLine();
                if ("q".equalsIgnoreCase(input)) {
                    System.exit(0);
                }
                System.out.println("\nEncoded output [ " + passwordEncoder.encode(input) + " ]\n");
            } catch (IOException e) {
                System.out.println("Error reading line " + e.getMessage());
            }
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder)

Example 23 with PasswordEncoder

use of org.springframework.security.crypto.password.PasswordEncoder in project hono by eclipse.

the class SpringBasedHonoPasswordEncoder method matches.

@Override
public boolean matches(final String rawPassword, final JsonObject credentialsOnRecord) {
    try {
        final EncodedPassword encodedPassword = EncodedPassword.fromHonoSecret(credentialsOnRecord);
        final PasswordEncoder encoder = Optional.ofNullable(encoders.get(encodedPassword.hashFunction)).orElse(encoderForEncode);
        return encoder.matches(rawPassword, encodedPassword.format());
    } catch (final IllegalArgumentException e) {
        // invalid Base64 scheme
        LOG.debug("error matching password", e);
        return false;
    }
}
Also used : BCryptPasswordEncoder(org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder)

Example 24 with PasswordEncoder

use of org.springframework.security.crypto.password.PasswordEncoder in project service-authorization by reportportal.

the class LdapAuthProvider method getDelegate.

@Override
protected AuthenticationProvider getDelegate() {
    Integration integration = integrationRepository.findAllByTypeIn(AuthIntegrationType.LDAP.getName()).stream().findFirst().orElseThrow(() -> new BadCredentialsException("LDAP is not configured"));
    DefaultSpringSecurityContextSource contextSource = new DefaultSpringSecurityContextSource(singletonList(LdapParameter.URL.getRequiredParameter(integration)), LdapParameter.BASE_DN.getRequiredParameter(integration));
    LdapParameter.MANAGER_PASSWORD.getParameter(integration).ifPresent(it -> contextSource.setPassword(encryptor.decrypt(it)));
    LdapParameter.MANAGER_DN.getParameter(integration).ifPresent(contextSource::setUserDn);
    contextSource.afterPropertiesSet();
    LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder> builder = new LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder>().contextSource(contextSource).ldapAuthoritiesPopulator(new NullLdapAuthoritiesPopulator()).userDetailsContextMapper(detailsContextMapper);
    /*
		 * Basically, groups are not used
		 */
    LdapParameter.GROUP_SEARCH_FILTER.getParameter(integration).ifPresent(builder::groupSearchFilter);
    LdapParameter.GROUP_SEARCH_BASE.getParameter(integration).ifPresent(builder::groupSearchBase);
    LdapParameter.USER_SEARCH_FILTER.getParameter(integration).ifPresent(builder::userSearchFilter);
    LdapParameter.PASSWORD_ENCODER_TYPE.getParameter(integration).ifPresent(it -> {
        LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder>.PasswordCompareConfigurer passwordCompareConfigurer = builder.passwordCompare();
        LdapParameter.PASSWORD_ATTRIBUTE.getParameter(integration).ifPresent(passwordCompareConfigurer::passwordAttribute);
        /*
			 * DIRTY HACK. If LDAP's password has solt, ldaptemplate.compare operation does not work
			 * since we don't know server's salt.
			 * To enable local password comparison, we need to provide password encoder from crypto's package
			 * This is why we just wrap old encoder with new one interface
			 * New encoder cannot be used everywhere since it does not have implementation for LDAP
			 */
        final PasswordEncoder delegate = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        builder.passwordEncoder(new org.springframework.security.crypto.password.PasswordEncoder() {

            @Override
            public String encode(CharSequence rawPassword) {
                return delegate.encode(rawPassword);
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return delegate.matches(rawPassword, encodedPassword);
            }
        });
    });
    LdapParameter.USER_DN_PATTERN.getParameter(integration).ifPresent(builder::userDnPatterns);
    try {
        return (AuthenticationProvider) Accessible.on(builder).method(LdapAuthenticationProviderConfigurer.class.getDeclaredMethod("build")).invoke();
    } catch (Throwable e) {
        throw new ReportPortalException("Cannot build LDAP auth provider", e);
    }
}
Also used : Integration(com.epam.ta.reportportal.entity.integration.Integration) DefaultSpringSecurityContextSource(org.springframework.security.ldap.DefaultSpringSecurityContextSource) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) AuthenticationProvider(org.springframework.security.authentication.AuthenticationProvider) BadCredentialsException(org.springframework.security.authentication.BadCredentialsException) PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) AuthenticationManagerBuilder(org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder) ReportPortalException(com.epam.ta.reportportal.exception.ReportPortalException) NullLdapAuthoritiesPopulator(org.springframework.security.ldap.authentication.NullLdapAuthoritiesPopulator) LdapAuthenticationProviderConfigurer(org.springframework.security.config.annotation.authentication.configurers.ldap.LdapAuthenticationProviderConfigurer)

Example 25 with PasswordEncoder

use of org.springframework.security.crypto.password.PasswordEncoder in project cas by apereo.

the class JdbcPasswordManagementService method change.

@Audit(action = "CHANGE_PASSWORD", actionResolverName = "CHANGE_PASSWORD_ACTION_RESOLVER", resourceResolverName = "CHANGE_PASSWORD_RESOURCE_RESOLVER")
@Override
public boolean change(final Credential credential, final PasswordChangeBean bean) {
    Assert.notNull(credential, "Credential cannot be null");
    Assert.notNull(bean, "PasswordChangeBean cannot be null");
    final UsernamePasswordCredential c = (UsernamePasswordCredential) credential;
    final PasswordEncoder encoder = Beans.newPasswordEncoder(passwordManagementProperties.getJdbc().getPasswordEncoder());
    final String password = encoder.encode(bean.getPassword());
    final int count = this.jdbcTemplate.update(passwordManagementProperties.getJdbc().getSqlChangePassword(), password, c.getId());
    return count > 0;
}
Also used : PasswordEncoder(org.springframework.security.crypto.password.PasswordEncoder) UsernamePasswordCredential(org.apereo.cas.authentication.UsernamePasswordCredential) Audit(org.apereo.inspektr.audit.annotation.Audit)

Aggregations

PasswordEncoder (org.springframework.security.crypto.password.PasswordEncoder)44 BCryptPasswordEncoder (org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder)24 NoOpPasswordEncoder (org.springframework.security.crypto.password.NoOpPasswordEncoder)10 Test (org.junit.jupiter.api.Test)9 UsernamePasswordAuthenticationToken (org.springframework.security.authentication.UsernamePasswordAuthenticationToken)7 KeystorePasswordHolder (won.owner.model.KeystorePasswordHolder)7 User (won.owner.model.User)7 SCryptPasswordEncoder (org.springframework.security.crypto.scrypt.SCryptPasswordEncoder)5 HashMap (java.util.HashMap)4 KeystoreHolder (won.owner.model.KeystoreHolder)4 ExpensiveSecureRandomString (won.protocol.util.ExpensiveSecureRandomString)4 IOException (java.io.IOException)3 Test (org.junit.Test)3 DataIntegrityViolationException (org.springframework.dao.DataIntegrityViolationException)3 UserDetails (org.springframework.security.core.userdetails.UserDetails)3 UserDetailsPasswordService (org.springframework.security.core.userdetails.UserDetailsPasswordService)3 UserDetailsService (org.springframework.security.core.userdetails.UserDetailsService)3 UsernameNotFoundException (org.springframework.security.core.userdetails.UsernameNotFoundException)3 Pbkdf2PasswordEncoder (org.springframework.security.crypto.password.Pbkdf2PasswordEncoder)3 UserEntity (com.zavada.entity.UserEntity)2