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.tamnd.app.rest.mvc.AccountControllerTest.java

@Test
public void createAccountNonExistingUsername() throws Exception {
    Account createdAccount = new Account();
    createdAccount.setUserId(1);/* ww w  . j a  v a2s  .  c  o m*/
    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:com.company.project.web.controller.service.CustomRememberMeUserDetailsService.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    try {/*from   w ww . j  av  a  2 s  . c om*/
        Map<String, String> user = new HashMap<String, String>();
        user.put("username", "admin");
        user.put("password", "");
        user.put("role", "ROLE_ADMIN");
        users.put("admin", user);
        user = new HashMap<String, String>();
        user.put("username", "sadmin");
        user.put("password", "");
        user.put("role", "ROLE_SYS_ADMIN");
        users.put("sadmin", user);
        user = new HashMap<String, String>();
        user.put("username", "user");
        user.put("password", "");
        user.put("role", "ROLE_USER");
        users.put("user", user);

        user = users.get(username);

        if (user == null) {
            return null;
        }

        List<GrantedAuthority> authorities = getAuthorities(user.get("role"));
        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        // BCryptPasswordEncoder automatically generates a salt and concatenates it.
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodedPassword = passwordEncoder.encode(user.get("password"));

        return new User(user.get("username"), encodedPassword, enabled, accountNonExpired,
                credentialsNonExpired, accountNonLocked, authorities);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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;
    }//from w ww .ja va2s  . 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:ch.wisv.areafiftylan.TeamRestIntegrationTest.java

@Before
public void initTeamTest() {
    teamCaptain = new User("captain", new BCryptPasswordEncoder().encode(teamCaptainCleartextPassword),
            "captain@mail.com");
    teamCaptain.getProfile().setAllFields("Captain", "Hook", "PeterPanKiller", Gender.MALE, "High Road 3",
            "2826ZZ", "Neverland", "0906-0777", null);

    teamCaptain = userRepository.saveAndFlush(teamCaptain);

    Ticket captainTicket = new Ticket(teamCaptain, TicketType.EARLY_FULL, false, false);
    captainTicket.setValid(true);//from w  w  w .  j a  v  a 2  s  .  c o m

    Ticket userTicket = new Ticket(user, TicketType.EARLY_FULL, false, false);
    userTicket.setValid(true);

    ticketRepository.save(captainTicket);
    ticketRepository.save(userTicket);

    team1.put("teamName", "testteam1");
}

From source file:no.ntnu.okse.web.WebSecurityConfig.java

public static boolean changeUserPassword(String password) {
    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
    String hashedPW = encoder.encode(password);
    try {// w w w .  java 2s  .c  o  m
        DB.conDB();
        DB.changePassword("admin", hashedPW);
    } catch (SQLException e) {
        log.debug("Unable to change password for admin user");
        return false;
    }
    return true;
}

From source file:cz.muni.fi.pa165.legomanager.services.impl.UserDetailsServiceImpl.java

@Secured({ "ROLE_ADMIN" })
public void createUser(UserTO user) {
    if (user == null)
        throw new IllegalArgumentException();
    PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    user.setPassword(passwordEncoder.encode(user.getPassword()));
    userDao.addUser(mapper.map(user, User.class));
}

From source file:com.companyname.providers.DAOAuthenticationProvider.java

protected void doAfterPropertiesSet() throws Exception {
    this.setUserDetailsService(userDetailsService);
    this.setPasswordEncoder(new BCryptPasswordEncoder());
    super.doAfterPropertiesSet();
}

From source file:ch.wisv.areafiftylan.IntegrationTest.java

private User makeUser() {
    User user = new User("user", new BCryptPasswordEncoder().encode(userCleartextPassword), "user@mail.com");
    user.getProfile().setAllFields("Jan", "de Groot", "MonsterKiller9001", Gender.MALE, "Mekelweg 4", "2826CD",
            "Delft", "0906-0666", null);

    return user;/*  w  w  w. j a v a 2  s . c o  m*/
}

From source file:com.toptal.entities.User.java

/**
 * Encrypts the password./*from  w  w  w . ja v  a 2  s.co  m*/
 */
@PrePersist
@PreUpdate
public final void encryptPassword() {
    if (this.password == null) {
        return;
    }
    this.password = new BCryptPasswordEncoder().encode(this.password);
}