Example usage for org.springframework.security.crypto.bcrypt BCryptPasswordEncoder BCryptPasswordEncoder

List of usage examples for org.springframework.security.crypto.bcrypt BCryptPasswordEncoder BCryptPasswordEncoder

Introduction

In this page you can find the example usage for org.springframework.security.crypto.bcrypt BCryptPasswordEncoder BCryptPasswordEncoder.

Prototype

public BCryptPasswordEncoder() 

Source Link

Usage

From source file:com.chevres.rss.restapi.controller.RegisterController.java

@CrossOrigin
@RequestMapping(path = "/register", method = RequestMethod.POST)
@ResponseBody/*  w ww  .  j a va  2s .c  om*/
public HttpEntity<String> register(@RequestBody User user, BindingResult bindingResult) {

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");

    userValidator.validate(user, bindingResult);

    if (bindingResult.hasErrors()) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("bad_params"), HttpStatus.BAD_REQUEST);
    }

    UserDAO userDAO = context.getBean(UserDAO.class);

    if (userDAO.doesExist(user.getUsername())) {
        context.close();
        return new ResponseEntity(new ErrorMessageResponse("already_exist"), HttpStatus.BAD_REQUEST);
    }

    PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    String hashedPassword = passwordEncoder.encode(user.getPassword());
    user.setPassword(hashedPassword);
    user.setType(User.USER_TYPE_LABEL);
    userDAO.create(user);

    context.close();

    return new ResponseEntity(new SuccessMessageResponse("success"), HttpStatus.OK);
}

From source file:ca.qhrtech.controllers.UserController.java

@ApiMethod(description = "Add a new User to BGL")
@RequestMapping(value = "/user", method = RequestMethod.POST)
public ResponseEntity<BGLUser> createUser(@RequestBody BGLUser user) {
    if (!userService.doesUserExist(user)) {
        user.setJoinDate(LocalDateTime.now());
        String hash = new BCryptPasswordEncoder().encode(user.getPassword());
        user.setPassword(hash);/*  w  w w  .j  a v  a2s .c o  m*/
        BGLUser newUser = userService.saveUser(user);
        return new ResponseEntity<>(newUser, HttpStatus.CREATED);
    }
    return new ResponseEntity<>(HttpStatus.CONFLICT);
}

From source file:ch.wisv.areafiftylan.security.authentication.AuthenticationServiceImpl.java

private boolean correctCredentials(User user, String password) {
    return new BCryptPasswordEncoder().matches(password, user.getPassword());
}

From source file:de.fau.amos4.configuration.SecurityConfiguration.java

/**
 * Authenticate using the the {@link UserDetailsService} and a hashed password.
 * /*from  ww  w . j a v  a 2 s  . co  m*/
 * @param auth
 * @throws Exception
 */
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}

From source file:com.chevres.rss.restapi.dao.impl.UserDAOImplTest.java

/**
 * Test of updateUser method, of class UserDAOImpl.
 *///  w w  w.ja  v  a 2 s.c o  m
@Test
public void testUpdateUser() {
    User oldUser = userDao.findByUsername("user1");
    User newUser = new User();
    newUser.setUsername("Anthony");
    newUser.setPassword("updatepwd");
    newUser.setType("admin");
    userDao.updateUser(oldUser, newUser, true);

    PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    boolean doesMatch = passwordEncoder.matches("updatepwd", oldUser.getPassword());

    assertEquals(oldUser.getUsername(), "Anthony");
    assertTrue(doesMatch);
    assertEquals(oldUser.getType(), "admin");
}

From source file:com.cami.persistence.service.impl.RoleService.java

@Override
public Role updateUser(final Role role) {

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    final Role userConnected = roleDao.retrieveAUser(auth.getName()); // get the current logged user
    final Role roleToUpdate = roleDao.findOne(role.getId());
    User userToUpdate;//from   w w w .java 2  s . c  o m
    System.out.println("updating user with ID " + role.getId());
    System.out.println("in updateUser service method ...");

    if (!userConnected.getRole().equals("ROLE_ADMIN")) {
        System.out.println("userConected is not admin launching his update of password ...");
        userToUpdate = userDao.findByUsername(userConnected.getUser().getUsername());
        System.out.println("his username is " + userToUpdate.getUsername());
        System.out.println("encrypting his password ...");
        userToUpdate.setPassword(passwordEncoder.encode(role.getUser().getPassword()));
        System.out.println(" password encrypted  \n Saving new configuration ....");
        userToUpdate = userDao.save(userToUpdate);
        System.out.println("configuration saved");
        roleToUpdate.setUser(userToUpdate);
        System.out.println("updating cache ....");
        return roleDao.save(roleToUpdate);
    } else {
        userToUpdate = role.getUser();
        userToUpdate.setEnabled(role.getUser().isEnabled());
        userToUpdate.setNom(role.getUser().getNom());
        userToUpdate.setUsername(role.getUser().getUsername());
        userToUpdate.setPassword(passwordEncoder.encode(role.getUser().getPassword()));
        userToUpdate = userDao.save(userToUpdate);

        final String vraiRole = getTheRealRoleOf(role.getRole());
        roleToUpdate.setUser(userToUpdate);
        roleToUpdate.setRole(vraiRole);
        System.out.println("in update service user role= " + roleToUpdate.getRole());
        System.out.println("updating ... ");
        Role r = roleDao.save(roleToUpdate);
        System.out.println("update finished");
        System.out.println("userToUpdate's username is " + r.getUser().getUsername());
        System.out.println("\n \n \n \n in updateUser service method displaying user updated ");
        System.out.println("deleteAction of a user =" + role.getId() + " -Role=" + role.getRole() + " username="
                + role.getUser().getUsername() + " enabled=" + role.getUser().isEnabled());

        return r;
    }

}

From source file:com.bac.accountserviceapp.data.mysql.MysqlAccountServiceAppTestAccountUser.java

@Before
public void setUp() {

    instance = appContext.getBean(MYSQL_ACCOUNT_ACCESSOR, MysqlAccountAccessor.class);
    instance.init();//from   ww  w. j a  v a  2 s .com
    encoder = new BCryptPasswordEncoder();
}

From source file:de.fau.amos4.test.integration.helper.security.WithMockCustomUserSecurityContextFactory.java

/**
 * Creates a client that has the details from the customUser.
 *
 * @param customUser/*  w w w.j  a  v a2s.  c  o m*/
 * @return A (otherwise empty) client.
 */
private Client createClient(WithMockCustomUser customUser) {
    // Create an empty client that is NOT in the database and populate it.
    Client client = new Client();
    client.setEmail(customUser.email());
    client.setPasswordHash(new BCryptPasswordEncoder().encode(customUser.password()));
    client.setRole(customUser.role());
    return client;
}

From source file:cz.zcu.kiv.eegdatabase.logic.controller.myaccount.ChangePasswordController.java

@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException bindException) throws Exception {
    ChangePasswordCommand changePasswordCommand = (ChangePasswordCommand) command;

    log.debug("Saving new password for actual user");
    String newPassword = changePasswordCommand.getNewPassword();
    String passwordHash = new BCryptPasswordEncoder().encode(newPassword);
    Person user = personDao.getPerson(ControllerUtils.getLoggedUserName());
    user.setPassword(passwordHash);//from w w  w.  jav a2  s  .  c om
    log.debug("Setting password hash [" + passwordHash + "] for user [" + user.getUsername() + "]");
    personDao.update(user);

    log.debug("Returning MAV");
    ModelAndView mav = new ModelAndView(getSuccessView());
    return mav;
}

From source file:de.fau.amos4.test.integration.ClientEditTest.java

@Test
@WithUserDetails("datev@example.com")
public void testThatClientEditSubmitChangesPassword() throws Exception {
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    Client client = new Client();
    client.setPasswordHash(encoder.encode("datev"));

    Mockito.doReturn(client).when(clientService).getClientByEmail(Matchers.<String>any());
    Assert.assertEquals(client, clientService.getClientByEmail("dfjashf"));

    mockMvc.perform(post("/client/edit/submit").with(csrf()).contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .param("NewPassword", "test").param("ConfirmPassword", "test").param("OldPassword", "datev")
            .sessionAttr("client", client)).andDo(print()).andExpect(status().is3xxRedirection())
            .andExpect(view().name("redirect:/client/dashboard?m=profileChanged"));
}