Java Code Examples for org.springframework.security.crypto.password.PasswordEncoder

The following examples show how to use org.springframework.security.crypto.password.PasswordEncoder. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Spring-Security-Third-Edition   Source File: SecurityConfig.java    License: MIT License 6 votes vote down vote up
/**
     * The PreAuthenticatedAuthenticationProvider does not process the {@link RolesAllowed} annotation.
     * @ param authenticationUserDetailsService
     * @return
     */
//    @Description("PreAuthenticatedAuthenticationProvider will return the existing Authentication token from the authenticate method")
//    @Bean
//    public PreAuthenticatedAuthenticationProvider preAuthAuthenticationProvider(final AuthenticationUserDetailsService authenticationUserDetailsService){
//        return new PreAuthenticatedAuthenticationProvider(){{
//            setPreAuthenticatedUserDetailsService(authenticationUserDetailsService);
//        }};
//    }

    @Description("AuthenticationMnager that will generate an authentication token unlike {@link PreAuthenticatedAuthenticationProvider}")
    @Bean @DependsOn({"defaultCalendarService"})
    public CalendarUserAuthenticationProvider calendarUserAuthenticationProvider(
            CalendarService calendarService,
            PasswordEncoder passwordEncoder){
        return new CalendarUserAuthenticationProvider(calendarService, passwordEncoder);
    }
 
Example 2
@Autowired
public DefaultCalendarService(final EventDao eventDao,
                              final CalendarUserDao userDao,
                              final CalendarUserRepository userRepository,
                              final PasswordEncoder passwordEncoder) {
    if (eventDao == null) {
        throw new IllegalArgumentException("eventDao cannot be null");
    }
    if (userDao == null) {
        throw new IllegalArgumentException("userDao cannot be null");
    }
    if (userRepository == null) {
        throw new IllegalArgumentException("userRepository cannot be null");
    }
    if (passwordEncoder == null) {
        throw new IllegalArgumentException("passwordEncoder cannot be null");
    }
    this.eventDao = eventDao;
    this.userDao = userDao;
    this.passwordEncoder = passwordEncoder;
}
 
Example 3
@Autowired
public DefaultCalendarService(final EventDao eventDao,
                              final CalendarUserDao userDao,
                              final CalendarUserRepository userRepository,
                              final PasswordEncoder passwordEncoder) {
    if (eventDao == null) {
        throw new IllegalArgumentException("eventDao cannot be null");
    }
    if (userDao == null) {
        throw new IllegalArgumentException("userDao cannot be null");
    }
    if (userRepository == null) {
        throw new IllegalArgumentException("userRepository cannot be null");
    }
    if (passwordEncoder == null) {
        throw new IllegalArgumentException("passwordEncoder cannot be null");
    }
    this.eventDao = eventDao;
    this.userDao = userDao;
    this.passwordEncoder = passwordEncoder;
}
 
Example 4
@Autowired
public DefaultCalendarService(final EventDao eventDao,
                              final CalendarUserDao userDao,
                              final CalendarUserRepository userRepository,
                              final PasswordEncoder passwordEncoder) {
    if (eventDao == null) {
        throw new IllegalArgumentException("eventDao cannot be null");
    }
    if (userDao == null) {
        throw new IllegalArgumentException("userDao cannot be null");
    }
    if (userRepository == null) {
        throw new IllegalArgumentException("userRepository cannot be null");
    }
    if (passwordEncoder == null) {
        throw new IllegalArgumentException("passwordEncoder cannot be null");
    }
    this.eventDao = eventDao;
    this.userDao = userDao;
    this.passwordEncoder = passwordEncoder;
}
 
Example 5
@Autowired
public DefaultCalendarService(final EventDao eventDao,
                              final CalendarUserDao userDao,
                              final PasswordEncoder passwordEncoder) {
    if (eventDao == null) {
        throw new IllegalArgumentException("eventDao cannot be null");
    }
    if (userDao == null) {
        throw new IllegalArgumentException("userDao cannot be null");
    }
    if (passwordEncoder == null) {
        throw new IllegalArgumentException("passwordEncoder cannot be null");
    }
    this.eventDao = eventDao;
    this.userDao = userDao;
    this.passwordEncoder = passwordEncoder;
}
 
Example 6
@Bean
public MapReactiveUserDetailsService reactiveUserDetailsService(
    ObjectProvider<PasswordEncoder> passwordEncoder
) {

    return new MapReactiveUserDetailsService(
        User.withUsername("user")
            .password("user")
            .passwordEncoder(p -> getOrDeducePassword(p, passwordEncoder.getIfAvailable()))
            .roles("USER")
            .build(),
        User.withUsername("admin")
            .password("admin")
            .passwordEncoder(p -> getOrDeducePassword(p, passwordEncoder.getIfAvailable()))
            .roles("USER", "ADMIN")
            .build()
    );
}
 
Example 7
Source Project: abixen-platform   Source File: User.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public void changePassword(String currentPassword, String newPassword) {
    final PasswordEncoder encoder = new BCryptPasswordEncoder();
    if (!encoder.matches(currentPassword, getPassword())) {
        throw new UsernameNotFoundException("Wrong username and / or password.");
    }

    setPassword(encoder.encode(newPassword));
}
 
Example 8
Source Project: ExamStack   Source File: UserAction.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 添加用户
 * 
 * @param user
 * @param groupId
 *            如果添加的用户为学员,必须指定groupId。如果添加的用户为教师,则groupId为任意数字
 * @return
 */
@RequestMapping(value = { "/add-user" }, method = RequestMethod.POST)
public @ResponseBody Message addUser(@RequestBody User user) {
	user.setCreateTime(new Date());
	
	String password = user.getPassword() + "{" + user.getUserName().toLowerCase() + "}";
	PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
	String resultPassword = passwordEncoder.encode(password);
	user.setPassword(resultPassword);
	user.setEnabled(true);
	user.setCreateBy(-1);
	user.setUserName(user.getUserName().toLowerCase());
	Message message = new Message();
	try {
		userService.addUser(user, "ROLE_STUDENT", 0, userService.getRoleMap());
	} catch (Exception e) {
		// TODO Auto-generated catch block

		if(e.getMessage().contains(user.getUserName())){
			message.setResult("duplicate-username");
			message.setMessageInfo("重复的用户名");
		} else if(e.getMessage().contains(user.getNationalId())){
			message.setResult("duplicate-national-id");
			message.setMessageInfo("重复的身份证");
		} else if(e.getMessage().contains(user.getEmail())){
			message.setResult("duplicate-email");
			message.setMessageInfo("重复的邮箱");
		} else if(e.getMessage().contains(user.getPhoneNum())){
			message.setResult("duplicate-phone");
			message.setMessageInfo("重复的电话");
		} else{
			message.setResult(e.getCause().getMessage());
			e.printStackTrace();
		}
	}
	return message;
}
 
Example 9
@Override
protected void setUp() throws Exception {
    super.setUp();
    DataSource dataSource = (DataSource) this.getApplicationContext().getBean("servDataSource");
    PasswordEncoder passwordEncoder = (PasswordEncoder) this.getApplicationContext().getBean("compatiblePasswordEncoder");
    UserDAO dao = new UserDAO();
    dao.setDataSource(dataSource);
    dao.setPasswordEncoder(passwordEncoder);
    this.userDao = dao;
}
 
Example 10
@Test
public void name () throws Exception {
	PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();


	for ( int i = 0 ; i < 10 ; i++ ) {
		System.err.println( passwordEncoder.encode( "123456" ) );
	}
}
 
Example 11
public TokenPasswordTokenIssuer(
        UserDetailsRepository users,
        PasswordEncoder passwordEncoder,
        TokenManager tokenManager) {
    this.users = users;
    this.passwordEncoder = passwordEncoder;
    this.tokenManager = tokenManager;
}
 
Example 12
@PreAuthorize("hasPermission(#id, '" + AclClassName.Values.LAYOUT + "', '" + PermissionName.Values.LAYOUT_EDIT + "')")
public LayoutDto changeLayoutIcon(final Long id, final MultipartFile iconFile) throws IOException {
    log.debug("changeLayoutIcon() - id: {}, iconFile: {}", id, iconFile);

    final Layout layout = layoutService.find(id);
    //FIXME - rename to thumbnail
    final File currentThumbnailFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory() + "/layout-miniature/" + layout.getIconFileName());

    if (currentThumbnailFile.exists()) {
        if (!currentThumbnailFile.delete()) {
            throw new FileExistsException();
        }
    }

    final PasswordEncoder encoder = new BCryptPasswordEncoder();
    final String newIconFileName = encoder.encode(iconFile.getName() + new Date().getTime()).replaceAll("\"", "s").replaceAll("/", "a").replace(".", "sde");
    final File newIconFile = new File(platformResourceConfigurationProperties.getImageLibraryDirectory() + "/layout-miniature/" + newIconFileName);

    final FileOutputStream out = new FileOutputStream(newIconFile);
    out.write(iconFile.getBytes());
    out.close();

    layout.changeIconFileName(newIconFileName);
    final Layout updatedLayout = layoutService.update(layout);

    return layoutToLayoutDtoConverter.convert(updatedLayout);
}
 
Example 13
@Test
public void standaloneIdmEngineWithDelegatingBCryptDefaultPasswordEncoder() {
    contextRunner
        .withPropertyValues("flowable.idm.password-encoder=spring_delegating_bcrypt")
        .run(context -> {
            IdmEngine idmEngine = context.getBean(IdmEngine.class);

            assertThat(context).hasSingleBean(PasswordEncoder.class);

            org.flowable.idm.api.PasswordEncoder flowablePasswordEncoder = idmEngine.getIdmEngineConfiguration().getPasswordEncoder();
            PasswordEncoder passwordEncoder = context.getBean(PasswordEncoder.class);
            assertThat(flowablePasswordEncoder)
                .isInstanceOfSatisfying(SpringEncoder.class, springEncoder -> {
                    assertThat(springEncoder.getSpringEncodingProvider()).isEqualTo(passwordEncoder);
                });
            assertThat(passwordEncoder).isInstanceOf(DelegatingPasswordEncoder.class);

            assertThat(flowablePasswordEncoder.encode("test", null))
                .as("encoded password")
                .startsWith("{bcrypt}");

            assertThat(flowablePasswordEncoder.isMatches("test", "test", null))
                .as("encoder matchers clear text password")
                .isFalse();

            assertThat(flowablePasswordEncoder.isMatches("test", new BCryptPasswordEncoder().encode("test"), null))
                .as("encoder matchers only bcrypt text password")
                .isTrue();
        });
}
 
Example 14
@Autowired
public CalendarUserAuthenticationProvider(final CalendarService calendarService,
                                          final PasswordEncoder passwordEncoder) {
    if (calendarService == null) {
        throw new IllegalArgumentException("calendarService cannot be null");
    }
    if (passwordEncoder == null) {
        throw new IllegalArgumentException("passwordEncoder cannot be null");
    }

    this.calendarService = calendarService;
    this.passwordEncoder = passwordEncoder;
}
 
Example 15
PasswordResetTokenRepositoryImpl(
    PasswordResetTokenFactory passwordResetTokenFactory,
    PasswordEncoder passwordEncoder,
    DataService dataService) {
  this.passwordResetTokenFactory = requireNonNull(passwordResetTokenFactory);
  this.passwordEncoder = requireNonNull(passwordEncoder);
  this.dataService = requireNonNull(dataService);
  this.tokenGenerator = new TokenGenerator();
}
 
Example 16
Source Project: webanno   Source File: WebAnno.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public PasswordEncoder passwordEncoder()
{
    // Set up a DelegatingPasswordEncoder which decodes legacy passwords using the
    // StandardPasswordEncoder but encodes passwords using the modern BCryptPasswordEncoder 
    String encoderForEncoding = "bcrypt";
    Map<String, PasswordEncoder> encoders = new HashMap<>();
    encoders.put(encoderForEncoding, new BCryptPasswordEncoder());
    DelegatingPasswordEncoder delegatingEncoder = new DelegatingPasswordEncoder(
            encoderForEncoding, encoders);
    // Decode legacy passwords without encoder ID using the StandardPasswordEncoder
    delegatingEncoder.setDefaultPasswordEncoderForMatches(new StandardPasswordEncoder());
    return delegatingEncoder;
}
 
Example 17
Source Project: ExamStack   Source File: UserAction.java    License: GNU General Public License v2.0 5 votes vote down vote up
@RequestMapping(value = { "/secure/update-user" }, method = RequestMethod.POST)
public @ResponseBody Message updateUser(@RequestBody User user) {
	//UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	user.setCreateTime(new Date());
	String password = user.getPassword() + "{" + user.getUserName() + "}";
	PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
	String resultPassword = "";
	if(user.getPassword() != null)
		resultPassword = "".equals(user.getPassword().trim()) ? "" : passwordEncoder.encode(password);
	user.setPassword(resultPassword);
	user.setEnabled(true);
	Message message = new Message();
	try {
		userService.updateUser(user, null);
	} catch (Exception e) {
		// TODO Auto-generated catch block

		if(e.getMessage().contains(user.getUserName())){
			message.setResult("duplicate-username");
			message.setMessageInfo("重复的用户名");
		} else if(e.getMessage().contains(user.getNationalId())){
			message.setResult("duplicate-national-id");
			message.setMessageInfo("重复的身份证");
		} else if(e.getMessage().contains(user.getEmail())){
			message.setResult("duplicate-email");
			message.setMessageInfo("重复的邮箱");
		} else if(e.getMessage().contains(user.getPhoneNum())){
			message.setResult("duplicate-phone");
			message.setMessageInfo("重复的电话");
		} else{
			message.setResult(e.getCause().getMessage());
			e.printStackTrace();
		}
	}
	return message;
}
 
Example 18
Source Project: ExamStack   Source File: UserActionAdmin.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 添加用户
 * 
 * @param user
 * @param groupId
 *            如果添加的用户为学员,必须指定groupId。如果添加的用户为教师,则groupId为任意数字
 * @return
 */
@RequestMapping(value = { "/admin/add-user-{authority}-{groupId}" }, method = RequestMethod.POST)
public @ResponseBody Message addUser(@RequestBody User user, @PathVariable String authority,
		@PathVariable Integer groupId) {
	UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	user.setCreateTime(new Date()); 
	String password = user.getPassword() + "{" + user.getUserName().toLowerCase() + "}";
	PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
	String resultPassword = passwordEncoder.encode(password);
	user.setPassword(resultPassword);
	user.setEnabled(true);
	user.setCreateBy(userInfo.getUserid());
	user.setUserName(user.getUserName().toLowerCase());
	Message message = new Message();
	try {
		userService.addUser(user, authority, groupId, userInfo.getRoleMap());
	} catch (Exception e) {
		// TODO Auto-generated catch block

		if(e.getMessage().contains(user.getUserName())){
			message.setResult("duplicate-username");
			message.setMessageInfo("重复的用户名");
		} else if(e.getMessage().contains(user.getNationalId())){
			message.setResult("duplicate-national-id");
			message.setMessageInfo("重复的身份证");
		} else if(e.getMessage().contains(user.getEmail())){
			message.setResult("duplicate-email");
			message.setMessageInfo("重复的邮箱");
		} else if(e.getMessage().contains(user.getPhoneNum())){
			message.setResult("duplicate-phone");
			message.setMessageInfo("重复的电话");
		} else{
			message.setResult(e.getCause().getMessage());
			e.printStackTrace();
		}
	}
	return message;
}
 
Example 19
Source Project: webanno   Source File: WebAnnoSecurity.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public WebAnnoSecurity(PasswordEncoder aPasswordEncoder,
        @Lazy AuthenticationManager aAuthenticationManager,
        @Lazy AuthenticationProvider aAuthenticationProvider, DataSource aDataSource,
        UserDao aUserRepository)
{
    passwordEncoder = aPasswordEncoder;
    authenticationManager = aAuthenticationManager;
    authenticationProvider = aAuthenticationProvider;
    dataSource = aDataSource;
    userRepository = aUserRepository;
}
 
Example 20
Source Project: forum   Source File: RegisterController.java    License: MIT License 4 votes vote down vote up
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
 
Example 21
Source Project: tutorials   Source File: MultipleAuthProvidersSecurityConfig.java    License: MIT License 4 votes vote down vote up
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
 
Example 22
Source Project: tutorials   Source File: SecurityConfiguration.java    License: MIT License 4 votes vote down vote up
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
 
Example 23
Source Project: ExamStack   Source File: SystemActionAdmin.java    License: GNU General Public License v2.0 4 votes vote down vote up
/**
 * 添加用户
 * 
 * @param user
 * @param groupId
 *            如果添加的用户为学员,必须指定groupId。如果添加的用户为教师,则groupId为任意数字
 * @return
 */
@RequestMapping(value = { "/admin/add-admin" }, method = RequestMethod.POST)
public @ResponseBody Message addUser(@RequestBody User user) {
	UserInfo userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	Message message = new Message();
	if(!userInfo.getAuthorities().toString().contains("ROLE_ADMIN")){
		message.setResult("权限错误!");
		message.setMessageInfo("只有管理员才可以添加管理员!");
		return message;
	}
	user.setCreateTime(new Date()); 
	String password = user.getPassword() + "{" + user.getUserName().toLowerCase() + "}";
	PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
	String resultPassword = passwordEncoder.encode(password);
	user.setPassword(resultPassword);
	user.setEnabled(true);
	user.setCreateBy(userInfo.getUserid());
	user.setUserName(user.getUserName().toLowerCase());
	
	try {
		userService.addUser(user, "ROLE_ADMIN", -1, userInfo.getRoleMap());
	} catch (Exception e) {
		// TODO Auto-generated catch block

		if(e.getMessage().contains(user.getUserName())){
			message.setResult("duplicate-username");
			message.setMessageInfo("重复的用户名");
		} else if(e.getMessage().contains(user.getNationalId())){
			message.setResult("duplicate-national-id");
			message.setMessageInfo("重复的身份证");
		} else if(e.getMessage().contains(user.getEmail())){
			message.setResult("duplicate-email");
			message.setMessageInfo("重复的邮箱");
		} else if(e.getMessage().contains(user.getPhoneNum())){
			message.setResult("duplicate-phone");
			message.setMessageInfo("重复的电话");
		} else{
			message.setResult(e.getCause().getMessage());
			e.printStackTrace();
		}
	}
	return message;
}
 
Example 24
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
 
Example 25
Source Project: Spring-Security-Third-Edition   Source File: SecurityConfig.java    License: MIT License 4 votes vote down vote up
/**
 * BCryptPasswordEncoder password encoder
 * @return
 */
@Description("Standard PasswordEncoder")
@Bean
public PasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder(4);
}
 
Example 26
public SecurityConfig(PasswordEncoder passwordEncoder,
    CredentialsDetailsService credentialUserDetails) {
  this.passwordEncoder = passwordEncoder;
  this.credentialUserDetails = credentialUserDetails;
}
 
Example 27
Source Project: Spring-Security-Third-Edition   Source File: SecurityConfig.java    License: MIT License 4 votes vote down vote up
/**
 * BCryptPasswordEncoder password encoder
 * @return
 */
@Bean
public PasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder(4);
}
 
Example 28
Source Project: Spring-Boot-2-Fundamentals   Source File: SecurityConfiguration.java    License: MIT License 4 votes vote down vote up
@Bean
public PasswordEncoder passwordEncoder() {
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
 
Example 29
Source Project: tutorials   Source File: SecurityConfiguration.java    License: MIT License 4 votes vote down vote up
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}
 
Example 30
@Bean
public PasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder();
}