Java org.springframework.security.authentication.encoding.PasswordEncoder 代码实例

・15 分钟阅读

以下是展示如何使用org.springframework.security.authentication.encoding.PasswordEncoder的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


/**
 * Password encryption test method for
 * {@link com.impetus.ankush.service.impl.UserManagerImpl#saveUser(com.impetus.ankush.common.domain.model.User)}
 * .
 * @throws UserExistsException 
 */
@Test
public void testSaveUserPasswordEncryptionChanged() throws UserExistsException {
        user.setVersion(1);
        user.setUsername(user.getUsername().toLowerCase());
        String encryptedPassword = "ENCRYPTED"+user.getPassword();
        PasswordEncoder passwordEncoder = EasyMock.createMock(PasswordEncoder.class);
        ((UserManagerImpl)userManager).setPasswordEncoder(passwordEncoder);
        EasyMock.expect(passwordEncoder.encodePassword(user.getPassword(), null)).andReturn(encryptedPassword);
        EasyMock.expect(userDao.getUserPassword(user.getUsername())).andReturn(user.getPassword()+"Old");
        EasyMock.expect(userDao.saveUser(user)).andReturn(user);
        EasyMock.replay(userDao, passwordEncoder);
        userManager.saveUser(user);
        assertEquals("password not encrypted", encryptedPassword, user.getPassword());
}
 

实例 2


@Test
public void shouldReturnPasswordType() throws Exception {
    // when
    PasswordEncoder passwordEncoder = mock(PasswordEncoder.class);
    FieldType fieldType = new PasswordType(passwordEncoder);
    // then
    assertEquals(String.class, fieldType.getType());
}
 

实例 3


@Test
public void testOldPWMigrate() {
    PasswordEncoder encoder = new Md5PasswordEncoder();
    String oldPW = encoder.encodePassword(STRING, null).toUpperCase();
    String newPW = PasswordUtils.updateOldEncPass(oldPW, DATESTRING);
    assertTrue("Old PW should match", PasswordUtils.isPasswordValid(newPW, STRING, DATESTRING));
}
 

实例 4


@Autowired public void setPasswordEncoder(Object passwordEncoder) {
    Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
    if (passwordEncoder instanceof PasswordEncoder) {
        setPasswordEncoder((PasswordEncoder) passwordEncoder);
        return;
    }
    if (passwordEncoder instanceof org.springframework.security.crypto.password.PasswordEncoder) {
        final org.springframework.security.crypto.password.PasswordEncoder delegate
            = (org.springframework.security.crypto.password.PasswordEncoder) passwordEncoder;
        // password encoder for admin.properties
        adminPasswordEncoder = delegate;
        setPasswordEncoder(new PasswordEncoder() {
            public String encodePassword(String rawPass, Object salt) {
                checkSalt(salt);
                return delegate.encode(rawPass);
            }
            public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
                checkSalt(salt);
                return delegate.matches(rawPass, encPass);
            }
            private void checkSalt(Object salt) {
                Assert.isNull(salt, "Salt value must be null when used with crypto module PasswordEncoder");
            }
        });
        return;
    }
    throw new IllegalArgumentException("passwordEncoder must be a PasswordEncoder instance");
}
 

实例 5


/** Returns an instance of password encoder.
 * The password are encoded in base64.
 * @return a password encoder.
 */
public PasswordEncoder getInstance() {
    if (passwordEncoderName.equalsIgnoreCase(MD5)) {
        Md5PasswordEncoder passwordEncoder = new Md5PasswordEncoder();
        passwordEncoder.setEncodeHashAsBase64(true);
        return passwordEncoder;
    } else if (passwordEncoderName.equalsIgnoreCase(SHA) || passwordEncoderName.equalsIgnoreCase(SSHA)) {
        ShaPasswordEncoder passwordEncoder = new ShaPasswordEncoder();
        passwordEncoder.setEncodeHashAsBase64(true);
        return passwordEncoder;
    } else {
        return new PlaintextPasswordEncoder();
    }
}
 

实例 6


@SuppressWarnings( "unchecked" )
public static void bind( final ServiceBinder binder ) {
    binder.bind( LogoutService.class, LogoutServiceImpl.class ).withMarker( SpringSecurityServices.class );
    binder.bind( AuthenticationTrustResolver.class, AuthenticationTrustResolverImpl.class ).withMarker(
            SpringSecurityServices.class );
    binder.bind( PasswordEncoder.class, PlaintextPasswordEncoder.class ).withMarker( SpringSecurityServices.class );
}
 

实例 7


@Override
protected PasswordEncoder getPasswordEncoder() {
    if (log.isDebugEnabled()) {
        log.debug("Invoking getPasswordEncoder");
    }
    return super.getPasswordEncoder();
}
 

实例 8


/**
 * User defined by the given userId gets a new password. Password is
 * generated by random and will be sent to the User via email.
 *
 * @param userId the ID of the {@link User} object in the database
 * @throws ShogunServiceException If an error arises
 */
@Transactional
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_SUPERADMIN')")
public void updateUserPassword(String userId) throws ShogunServiceException {
        User user = null;
        try {
                // create an integer out of the id-String
                int iUserId = Integer.parseInt(userId);
                // get the User object
                user = (User) this.getDatabaseDao().getEntityById(iUserId, User.class);
        } catch (Exception e) {
                throw new ShogunServiceException(
                                "Error while getting User from database with ID " +
                                userId + " " + e.getMessage());
        }
        try {
                // set the new password
                String newPassword = Password.getRandomPassword(8);
                PasswordEncoder pwencoder = new Md5PasswordEncoder();
                String hashed = pwencoder.encodePassword(newPassword, null);
                user.setUser_password(hashed);
                // write back to database
                this.getDatabaseDao().updateUser(user);
                // send an email with the new password
                //TODO remove static texts
                //TODO remove static mail server settings
                String mailtext = "Sehr geehrter Nutzer " + user.getUser_name()
                                + "nn";
                mailtext += "Ihr SHOGun-Passwort wurde geändert und lautet nn";
                mailtext += newPassword + "nn";
                Mail.send("localhost", 25, user.getUser_email(),
                                "admin", "Passwort-Änderung bei SHOGun", mailtext);
        } catch (Exception e) {
                throw new ShogunServiceException(
                                "Error while updating User in database or while " +
                                "sending email. " + e.getMessage());
        }
}
 

实例 9


protected PasswordEncoder getStringEncoder() {
    if (stringEncoder == null) {
        synchronized (this) {
            if (stringEncoder == null) {
                stringEncoder = createStringEncoder();
            }
        }
    }
    return stringEncoder;
}
 

实例 10


public UserServiceImpl( PasswordEncoder encoder, SaltSource salt ) {
        this.encoder = encoder;
        this.salt = salt;
    //admin = new User( "admin" );
    //admin.addAuthority( user );
    //admin.addAuthority( new GrantedAuthorityImpl( "ROLE_ADMIN" ) );
    //admin.setPassword( encoder.encodePassword( "admin", salt.getSalt( admin ) ) );
}
 

实例 11


@Test
public void testSetPasswordEncoder() {
        org.springframework.security.authentication.encoding.PasswordEncoder enc1 = new PlaintextPasswordEncoder();
        provider.setPasswordEncoder(enc1);
        org.springframework.security.crypto.password.PasswordEncoder enc2 = new StandardPasswordEncoder();
        provider.setPasswordEncoder(enc2);
        provider.setPasswordEncoder(passwordEncoder);
}
 

实例 12


public User createUser(final User user) throws UnauthorizedException {
    User requestingUser = getCurrentUser();
    if (requestingUser != null && !requestingUser.isAdmin()) {
        throw new UnauthorizedException("Only admins can create new accounts!");
    }
    tt.execute(new TransactionCallbackWithoutResult() {
        public void doInTransactionWithoutResult(TransactionStatus status) {
            boolean success = false;
            try {
                PasswordEncoder encoder = new ShaPasswordEncoder();
                String hashedPass = encoder.encodePassword(user.getPassword(), null);
                user.setId(insert(
                        "INSERT INTO Users (username, password, enabled) "
                        + "VALUES (?, ?, ?)", user.getName(),
                        hashedPass, user.isEnabled()));
                addAuthority(user.getName(), ROLE_USER);
                if (user.isAdmin()) {
                    addAuthority(user.getName(), ROLE_ADMIN);
                }
                success = true;
            } finally {
                if (!success) {
                    status.setRollbackOnly();
                }
            }
        }
    });
    return user;
}
 

实例 13


@Autowired
public JdbcHQAuthenticationProvider(PrincipalDAO principalDao,
                                    AuthzSubjectManager authzSubjectManager,
                                    PasswordEncoder passwordEncoder) {
    this.principalDao = principalDao;
    this.authzSubjectManager = authzSubjectManager;
    this.passwordEncoder = passwordEncoder;
}
 

实例 14


public AlexisWebAuthenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder,
        UserDao userDao, PlatformTransactionManager transactionManager) {
    this.userDetailsService = userDetailsService;
    this.passwordEncoder = passwordEncoder;
    this.userDao = userDao;
    this.transactionManager = transactionManager;
    this.transactionTemplate = new TransactionTemplate(this.transactionManager);
}
 

实例 15


private void createSystemNodes() throws RepositoryException {
        LOG.info("Creating system nodes");
       Node rootNode = getTemplate().getRootNode();
       Node nextServerNode = rootNode.addNode(StorageConstants.NEXT_SERVER_FOLDER_NAME);
       nextServerNode.addMixin("mix:referenceable");
       nextServerNode.setProperty("className", Folder.class.getName());
       nextServerNode.setProperty("version", "-1");
       Node reportsNode = nextServerNode.addNode(StorageConstants.REPORTS_FOLDER_NAME);
       reportsNode.addMixin("mix:referenceable");
       reportsNode.setProperty("className", Folder.class.getName());
       Node datasourcesNode = nextServerNode.addNode(StorageConstants.DATASOURCES_FOLDER_NAME);
       datasourcesNode.addMixin("mix:referenceable");
       datasourcesNode.setProperty("className", Folder.class.getName());
       Node schedulersNode = nextServerNode.addNode(StorageConstants.SCHEDULER_FOLDER_NAME);
       schedulersNode.addMixin("mix:referenceable");
       schedulersNode.setProperty("className", Folder.class.getName());
       Node securityNode = nextServerNode.addNode(StorageConstants.SECURITY_FOLDER_NAME);
       securityNode.addMixin("mix:referenceable");
       securityNode.setProperty("className", Folder.class.getName());
       Node usersNode = securityNode.addNode(StorageConstants.USERS_FOLDER_NAME);
       usersNode.addMixin("mix:referenceable");
       usersNode.setProperty("className", Folder.class.getName());
       Node groupsNode = securityNode.addNode(StorageConstants.GROUPS_FOLDER_NAME);
       groupsNode.addMixin("mix:referenceable");
       groupsNode.setProperty("className", Folder.class.getName());
       Node adminNode = usersNode.addNode(StorageConstants.ADMIN_USER_NAME);
       adminNode.addMixin("mix:referenceable");
       adminNode.setProperty("className", User.class.getName());
       adminNode.setProperty("admin", true);
       PasswordEncoder passwordEncoder = new Md5PasswordEncoder();
       adminNode.setProperty("password", passwordEncoder.encodePassword("1", null));
       getTemplate().save();
}
 
讨论
淘淘あ西西 profile image