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

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

Introduction

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

Prototype

public boolean matches(CharSequence rawPassword, String encodedPassword) 

Source Link

Usage

From source file:com.mycompany.fitness_tracker_servlet_maven.core.PasswordEncoder.java

protected static boolean passwordMatch(String inputPassword, String storedHashedPassword) {
    log.trace("passwordMatch");
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(PASSWORD_STRENGTH);
    return passwordEncoder.matches(inputPassword, storedHashedPassword);
}

From source file:com.jcs.goboax.aulavirtual.dao.impl.UsuarioDaoImpl.java

@Override
public Usuario getByCredentials(Integer aUserId, String aPassword) {
    Usuario myUsuario = findByKey(aUserId);
    if (myUsuario != null) {
        BCryptPasswordEncoder myBCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean isValid = myBCryptPasswordEncoder.matches(aPassword, myUsuario.getPassword());
        if (isValid) {
            return myUsuario;
        }//from ww w.  j a v  a 2  s. co m
    }
    return null;
}

From source file:com.katropine.oauth.CustomUserAuthenticationProvider.java

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    LOGGER.warning("!!!Authenticate: " + authentication.getPrincipal().toString() + ":"
            + authentication.getCredentials().toString());

    if (!supports(authentication.getClass())) {
        return null;
    }/*w w  w  .  j av  a2  s  . c  o  m*/
    if (authentication.getCredentials() == null) {
        LOGGER.warning("No credentials found in request.");
        boolean throwExceptionWhenTokenRejected = false;
        if (throwExceptionWhenTokenRejected) {
            throw new BadCredentialsException("No pre-authenticated credentials found in request.");
        }
        return null;
    }

    User user = userDAO.getByEmail(authentication.getPrincipal().toString());

    BCryptPasswordEncoder enc = new BCryptPasswordEncoder();
    if (!enc.matches(authentication.getCredentials().toString(), user.getPassword())) {
        throw new BadCredentialsException("Bad User Credentials.");
    }

    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    CustomUserPasswordAuthenticationToken auth = new CustomUserPasswordAuthenticationToken(
            authentication.getPrincipal(), authentication.getCredentials(), grantedAuthorities);

    return auth;

}

From source file:com.tamnd.app.rest.mvc.AccountControllerTest.java

@Test
public void createAccountNonExistingUsername() throws Exception {
    Account createdAccount = new Account();
    createdAccount.setUserId(1);//from   w  ww  . j  a v  a  2s  .c om
    createdAccount.setPassword("test");
    createdAccount.setUserName("test");

    when(service.createAccount(any(Account.class))).thenReturn(createdAccount);

    mockMvc.perform(post("/rest/accounts").content("{\"userName\":\"test\",\"password\":\"test\"}")
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(header().string("Location", endsWith("/rest/accounts/1")))
            .andExpect(jsonPath("$.userName", is(createdAccount.getUserName())))
            .andExpect(status().isCreated());

    verify(service).createAccount(accountCaptor.capture());

    String password = accountCaptor.getValue().getPassword();
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    assertTrue(passwordEncoder.matches("test", password));
}

From source file:edu.mum.managedBean.LoginManagedBean.java

public User checkCredentials() {
    List<User> users = userService.findAll();
    ////from   ww  w.j  ava  2 s  . c o  m
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    for (User user : users) {
        boolean passwordMatch = encoder.matches(credentialBean.getPassword(),
                user.getCredentials().getPassword());
        if (user.getCredentials().getUsername().equalsIgnoreCase(credentialBean.getUsername())
                && passwordMatch) {
            return user;
        }
    }
    return null;
}

From source file:com.cristian.tareask.controller.ProfileController.java

@RequestMapping(value = "/editprofile", method = RequestMethod.POST)
public String editProfile(HttpSession session, @RequestParam(value = "name") String name,
        @RequestParam(value = "subname") String subname, @RequestParam(value = "birthdate") String birthdate,
        @RequestParam(value = "phone") String phone, @RequestParam(value = "oldpassword") String oldpassword,
        @RequestParam(value = "newpassword") String newpassword, final RedirectAttributes redirectAttrs)
        throws ParseException {

    if ((session.getAttribute("namesession")) != null) {

        User u = new User();

        u = userService.getUserByName(session.getAttribute("namesession").toString());
        if (name == null || subname == null || birthdate == null || phone == null) {
            redirectAttrs.addFlashAttribute("editprofile", "Ups!. Unable to to update information.");
            return "redirect:profile.html";
        }/* w w w  .  ja  va2  s  .  c o m*/

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = formatter.parse(birthdate);
        u.setName(name);
        u.setSubname(subname);
        u.setBirthdate(date);
        int phonenumber = Integer.parseInt(phone);
        u.setPhone(phonenumber);

        if (!"".equals(oldpassword) & !"".equals(newpassword)) {
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String hashedOldPassword = passwordEncoder.encode(oldpassword);
            System.out.println(hashedOldPassword);
            if (passwordEncoder.matches(oldpassword, u.getPassword())) {
                String hashedNewPassword = passwordEncoder.encode(newpassword);
                u.setPassword(hashedNewPassword);
            } else {
                redirectAttrs.addFlashAttribute("editprofile", "You must enter your old password.");
                return "redirect:profile.html";
            }

        }
        userService.edit(u);
        redirectAttrs.addFlashAttribute("editprofile", "Your profile has been updated!");
        session.setAttribute("namesession", u.getName());
        return "redirect:profile.html";
    }
    return "";
}

From source file:au.aurin.org.controller.RestController.java

@RequestMapping(method = RequestMethod.POST, value = "/changeoldpassword")
public @ResponseBody Boolean changeoldPassword(@RequestHeader("uuid") final String uuid,
        @RequestHeader("oldpassword") final String oldpassword,
        @RequestHeader("newpassword") final String newpassword, final HttpServletRequest request) {
    try {//from  ww  w. ja  va2s  . c  om
        logger.info("*******>> changeoldpassword for uuid={}  ", uuid);
        final String password = geodataFinder.getPassID(uuid);
        if (password.length() > 0) {

            final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

            final boolean isMatch = passwordEncoder.matches(oldpassword, password);

            if (isMatch == true) {
                logger.info("*******>> changeoldpassword passwords are match. now assigning new password. ");
                final String hashednewPassword = passwordEncoder.encode(newpassword);
                return geodataFinder.changeuuidPassword(uuid, hashednewPassword);
            }
        }

    } catch (final Exception e) {
        logger.info("Error in changeoldPassword is : " + e.toString());

    }
    return false;
}

From source file:au.aurin.org.controller.RestController.java

@RequestMapping(method = RequestMethod.GET, value = "/getUser", produces = "application/json")
@ResponseStatus(HttpStatus.OK)/*from  ww  w  .  j a  va  2s  .  c o  m*/
public @ResponseBody userData getUser(@RequestHeader("X-AURIN-USER-ID") final String roleId,
        @RequestHeader("user") final String user, @RequestHeader("password") final String password,
        final HttpServletRequest request) {

    if (!roleId.equals(adminUser.getAdminUsername())) {
        logger.info("Incorrect X-AURIN-USER-ID passed: {}.", roleId);
        return null;
    }

    logger.info("*******>> Rest-getUser for Project user ={} and pass={} ", user, password);
    userData myuser = new userData();

    try {

        final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        myuser = geodataFinder.getUser(user);
        if (myuser != null) {
            final boolean isMatch = passwordEncoder.matches(password, myuser.getPassword());

            if (isMatch == true) {
                // final HttpSession session = request.getSession(true);
                // session.setAttribute("user_id", "1");
                // session.setAttribute("user_name", "Alireza Shamakhy");
                // session.setAttribute("user_org", "Maroondah");
                myuser.setPassword("");
                return myuser;
            } else {
                return null;
            }
        } else {
            return null;
        }

    } catch (final Exception e) {
        logger.info(e.toString());
        logger.info("*******>> Error in Rest-getUser for  user ={}  ", user);

    }
    return null;
}

From source file:au.aurin.org.controller.RestController.java

@RequestMapping(method = RequestMethod.GET, value = "/getUserOne", produces = "application/json")
@ResponseStatus(HttpStatus.OK)/*  w  w  w .j  av a  2  s  .c o m*/
public @ResponseBody userDataOne getUserOne(@RequestHeader("X-AURIN-USER-ID") final String roleId,
        @RequestHeader("user") final String user, @RequestHeader("password") final String password,
        final HttpServletRequest request) {

    if (!roleId.equals(adminUser.getAdminUsername())) {
        logger.info("Incorrect X-AURIN-USER-ID passed: {}.", roleId);
        return null;
    }

    logger.info("*******>> Rest-getUser for Project user ={} and pass={} ", user, password);
    final userDataOne myuser = new userDataOne();

    try {

        final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (geodataFinder.getUser(user) != null) {
            myuser.setUser_id(geodataFinder.getUser(user).getUser_id());
            myuser.setPassword(geodataFinder.getUser(user).getPassword());
            myuser.setEmail(geodataFinder.getUser(user).getEmail());

            final boolean isMatch = passwordEncoder.matches(password, myuser.getPassword());

            if (isMatch == true) {
                // final HttpSession session = request.getSession(true);
                // session.setAttribute("user_id", "1");
                // session.setAttribute("user_name", "Alireza Shamakhy");
                // session.setAttribute("user_org", "Maroondah");
                myuser.setPassword("");
                return myuser;
            } else {
                return null;
            }
        } else {
            return null;
        }

    } catch (final Exception e) {
        logger.info(e.toString());
        logger.info("*******>> Error in Rest-getUser for Project user ={} and pass={} ", user, password);

    }
    return null;
}