Java Code Examples for org.springframework.security.crypto.password.PasswordEncoder#matches()

The following examples show how to use org.springframework.security.crypto.password.PasswordEncoder#matches() . 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 File: AdminServiceImpl.java    From mogu_blog_v2 with Apache License 2.0 6 votes vote down vote up
@Override
public String changePwd(String oldPwd, String newPwd) {
    HttpServletRequest request = RequestHolder.getRequest();
    if (request.getAttribute(SysConf.ADMIN_UID) == null || request.getAttribute(SysConf.ADMIN_UID) == "") {
        return ResultUtil.result(SysConf.ERROR, MessageConf.INVALID_TOKEN);
    }
    if (StringUtils.isEmpty(oldPwd) || StringUtils.isEmpty(newPwd)) {
        return ResultUtil.result(SysConf.ERROR, MessageConf.PARAM_INCORRECT);
    }

    Admin admin = adminService.getById(request.getAttribute(SysConf.ADMIN_UID).toString());

    PasswordEncoder encoder = new BCryptPasswordEncoder();

    boolean isPassword = encoder.matches(oldPwd, admin.getPassWord());

    if (isPassword) {
        admin.setPassWord(encoder.encode(newPwd));
        admin.setUpdateTime(new Date());
        admin.updateById();
        return ResultUtil.result(SysConf.SUCCESS, MessageConf.UPDATE_SUCCESS);
    } else {
        return ResultUtil.result(SysConf.ERROR, MessageConf.ERROR_PASSWORD);
    }
}
 
Example 2
Source File: AuthRestApi.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
@OperationLogger(value = "更新管理员密码")
@ApiOperation(value = "更新管理员密码", notes = "更新管理员密码")
@PostMapping("/updatePassWord")
public String updatePassWord(HttpServletRequest request,
                             @ApiParam(name = "userInfo", value = "管理员账户名", required = true) @RequestParam(name = "userInfo", required = true) String userInfo,
                             @ApiParam(name = "passWord", value = "管理员旧密码", required = true) @RequestParam(name = "passWord", required = true) String passWord,
                             @ApiParam(name = "newPassWord", value = "管理员新密码", required = true) @RequestParam(name = "newPassWord", required = true) String newPassWord) {
    QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
    if (CheckUtils.checkEmail(userInfo)) {
        queryWrapper.eq(SQLConf.EMAIL, userInfo);
    } else if (CheckUtils.checkMobileNumber(userInfo)) {
        queryWrapper.eq(SQLConf.MOBILE, userInfo);
    } else {
        queryWrapper.eq(SQLConf.USER_NAME, userInfo);
    }
    Admin admin = adminService.getOne(queryWrapper);
    if (admin == null) {
        return ResultUtil.result(SysConf.ERROR, "管理员不存在");
    }
    if (StringUtils.isEmpty(passWord)) {
        return ResultUtil.result(SysConf.ERROR, "旧密码不能为空");
    }
    if (StringUtils.isEmpty(newPassWord)) {
        return ResultUtil.result(SysConf.ERROR, "新密码不能为空");
    }
    String uid = admin.getUid();

    PasswordEncoder encoder = new BCryptPasswordEncoder();
    boolean isPassword = encoder.matches(passWord, admin.getPassWord());
    if (isPassword) {
        admin.setPassWord(encoder.encode(newPassWord));
        UpdateWrapper<Admin> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq(SQLConf.UID, uid);
        admin.setUpdateTime(new Date());
        adminService.update(admin, updateWrapper);
        return ResultUtil.result(SysConf.SUCCESS, "密码更新成功");
    }
    return ResultUtil.result(SysConf.ERROR, "旧密码错误");
}
 
Example 3
Source File: SpringBasedHonoPasswordEncoder.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean matches(final String rawPassword, final JsonObject credentialsOnRecord) {

    try {
        final EncodedPassword encodedPassword = EncodedPassword.fromHonoSecret(credentialsOnRecord);
        final PasswordEncoder encoder = Optional.ofNullable(encoders.get(encodedPassword.hashFunction)).orElse(encoderForEncode);
        return encoder.matches(rawPassword, encodedPassword.format());
    } catch (final IllegalArgumentException e) {
        // invalid Base64 scheme
        LOG.debug("error matching password", e);
        return false;
    }
}
 
Example 4
Source File: AuthenticationFilter.java    From ExamStack with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

	if(!request.getMethod().equals("POST")){
		throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
	}
	String username = this.obtainUsername(request);
	String password = this.obtainPassword(request);
	
	//加盐
	String sh1Password = password + "{" + username + "}";
	PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
	String result = passwordEncoder.encode(sh1Password);
	log.info(result);
	UserInfo userDetails = (UserInfo) userDetailsService.loadUserByUsername(username);
	
	
	/*this.checkValidateCode(request);*/
	if(!passwordEncoder.matches(userDetails.getPassword(), result) || "0".equals(userDetails.getEnabled()) || userDetails == null){
		//System.out.println("用户名或密码错误!");
		throw new AuthenticationServiceException("用户名或密码错误!");
	}
	if(!userDetails.getRolesName().contains("ROLE_ADMIN") && !userDetails.getRolesName().contains("ROLE_TEACHER")){
		throw new AuthenticationServiceException("非管理用户,操作无效!");
	}
	UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
	this.setDetails(request, authRequest);
	Authentication authentication = null;
	try{
		authentication = this.getAuthenticationManager().authenticate(authRequest);
	}catch(Exception e){
		e.printStackTrace();
	}
	
	return authentication;
}
 
Example 5
Source File: User.java    From abixen-platform with 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 6
Source File: AuthenticationFilter.java    From ExamStack with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

	if(!request.getMethod().equals("POST")){
		throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
	}
	String username = this.obtainUsername(request);
	String password = this.obtainPassword(request);
	
	//加盐
	String sh1Password = password + "{" + username + "}";
	PasswordEncoder passwordEncoder = new StandardPasswordEncoderForSha1();
	String result = passwordEncoder.encode(sh1Password);
	log.info(result);
	UserInfo userDetails = (UserInfo) userDetailsService.loadUserByUsername(username);
	
	
	/*this.checkValidateCode(request);*/
	if(!passwordEncoder.matches(userDetails.getPassword(), result) || "0".equals(userDetails.getEnabled()) || userDetails == null){
		//System.out.println("用户名或密码错误!");
		throw new AuthenticationServiceException("用户名或密码错误!");
	}
	if(!userDetails.getRolesName().contains("ROLE_ADMIN") && !userDetails.getRolesName().contains("ROLE_TEACHER")){
		throw new AuthenticationServiceException("非管理用户,操作无效!");
	}
	UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
	this.setDetails(request, authRequest);
	Authentication authentication = null;
	try{
		authentication = this.getAuthenticationManager().authenticate(authRequest);
	}catch(Exception e){
		e.printStackTrace();
	}
	
	return authentication;
}
 
Example 7
Source File: PasswordUpdateController.java    From wallride with Apache License 2.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.PUT)
public String update(
		@Validated @ModelAttribute(FORM_MODEL_KEY) PasswordUpdateForm form,
		BindingResult errors,
		AuthorizedUser authorizedUser,
		RedirectAttributes redirectAttributes) {
	redirectAttributes.addFlashAttribute(FORM_MODEL_KEY, form);
	redirectAttributes.addFlashAttribute(ERRORS_MODEL_KEY, errors);

	if (!errors.hasFieldErrors("newPassword")) {
		if (!ObjectUtils.nullSafeEquals(form.getNewPassword(), form.getNewPasswordRetype())) {
			errors.rejectValue("newPasswordRetype", "MatchRetype");
		}
	}

	if (!errors.hasErrors()) {
		User user = userService.getUserById(authorizedUser.getId());
		PasswordEncoder passwordEncoder = new StandardPasswordEncoder();
		if (!passwordEncoder.matches(form.getCurrentPassword(), user.getLoginPassword())) {
			errors.rejectValue("currentPassword", "MatchCurrentPassword");
		}
	}

	if (errors.hasErrors()) {
		return "redirect:/settings/password?step.edit";
	}

	PasswordUpdateRequest request = new PasswordUpdateRequest()
			.withUserId(authorizedUser.getId())
			.withPassword(form.getNewPassword());
	userService.updatePassword(request, authorizedUser);

	redirectAttributes.getFlashAttributes().clear();
	redirectAttributes.addFlashAttribute("updatedPassword", true);
	return "redirect:/settings/password";
}