下面列出了怎么用org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(String...args) {
System.setProperty("spring.config.name", "tailstreamer");
System.setProperty("spring.config.location", "../conf/");
ArgumentProcessor argumentProcessor = new ArgumentProcessor();
if (argumentProcessor.parseArguments(args) && argumentProcessor.validateArguments()) {
OptionSet options = argumentProcessor.getOptions();
if (options.has("h")) {
System.out.println(getHelpText());
} else if (options.has("v")) {
System.out.println("TailStreamer version " + VERSION);
} else if (options.has("encryptPassword")) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
System.out.println(encoder.encode((String) options.nonOptionArguments().get(0)));
} else {
TailStreamerApplication app = new TailStreamerApplication(TailStreamer.class, argumentProcessor.getOptions());
app.run(args);
}
} else {
System.err.println(argumentProcessor.getValidationErrorMessage());
System.out.println(getHelpText());
System.exit(1);
}
}
public static void main(String[] args) {
if (args.length != 2) {
printUsage();
System.exit(1);
}
String encryptMethod = args[0];
String passwordTxt = args[1];
if ("AES".equalsIgnoreCase(encryptMethod)) {
// for encrypt password like LDAP password
System.out.println(encryptMethod + " encrypted password is: ");
System.out.println(EncryptUtil.encrypt(passwordTxt));
} else if ("BCrypt".equalsIgnoreCase(encryptMethod)) {
// for encrypt the predefined user password, like ADMIN, MODELER.
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
System.out.println(encryptMethod + " encrypted password is: ");
System.out.println(bCryptPasswordEncoder.encode(passwordTxt));
} else {
printUsage();
System.exit(1);
}
}
@Test
public void standaloneIdmEngineWithBCryptPasswordEncoder() {
contextRunner
.withPropertyValues("flowable.idm.password-encoder=spring_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(BCryptPasswordEncoder.class);
});
}
@AuthorityVerify
@OperationLogger(value = "重置用户密码")
@ApiOperation(value = "重置用户密码", notes = "重置用户密码")
@PostMapping("/restPwd")
public String restPwd(HttpServletRequest request,
@ApiParam(name = "uid", value = "管理员uid", required = true) @RequestParam(name = "uid", required = false) String uid) {
if (StringUtils.isEmpty(uid)) {
return ResultUtil.result(SysConf.ERROR, MessageConf.PARAM_INCORRECT);
}
Admin admin = adminService.getById(uid);
PasswordEncoder encoder = new BCryptPasswordEncoder();
admin.setPassWord(encoder.encode(DEFAULE_PWD));
admin.setUpdateTime(new Date());
admin.updateById();
return ResultUtil.result(SysConf.SUCCESS, MessageConf.UPDATE_SUCCESS);
}
/**
* 更改密码
* @param code
* @param password
* @param responseMsgVO
*/
public void changePwd(String code, String password, ResponseMsgVO responseMsgVO) {
String username= UserContextHandler.getUsername();
UserDO userDO = userRepository.findByUsername(username);
log.info("用户:{}更改密码",userDO.getUsername());
String key = CODE_PREFIX + CodeTypeEnum.CHANGE_PWD.getValue() + userDO.getEmail();
String value = redisTemplate.opsForValue().get(key);
if (!StringUtils.equals(code, value)) {
responseMsgVO.buildWithMsgAndStatus(PosCodeEnum.PARAM_ERROR, "验证码错误");
return;
}
if (!checkPassWordLegal(password, responseMsgVO)){
return;
}
// 更新到mongo数据库
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
WriteResult result = userRepository.changePassword(username, passwordEncoder.encode(password));
if (result.getN() == 0) {
responseMsgVO.buildWithMsgAndStatus(PosCodeEnum.PARAM_ERROR, "更新失败");
return;
}
responseMsgVO.buildOK();
}
public void changeAvatar(String imageLibraryDirectory, MultipartFile avatarFile) throws IOException {
final File currentAvatarFile = new File(imageLibraryDirectory + "/user-avatar/" + getAvatarFileName());
if (currentAvatarFile.exists()) {
if (!currentAvatarFile.delete()) {
throw new FileExistsException();
}
}
final PasswordEncoder encoder = new BCryptPasswordEncoder();
final String newAvatarFileName = encoder.encode(avatarFile.getName() + new Date().getTime()).replaceAll("\"", "s").replaceAll("/", "a").replace(".", "sde");
final File newAvatarFile = new File(imageLibraryDirectory + "/user-avatar/" + newAvatarFileName);
final FileOutputStream out = new FileOutputStream(newAvatarFile);
out.write(avatarFile.getBytes());
out.close();
setAvatarFileName(newAvatarFileName);
}
@Autowired
public InternalAuthenticationProvider(SCIMUserProvisioning userProvisioning,
ShaPasswordEncoder shaPasswordEncoder,
BCryptPasswordEncoder bCryptPasswordEncoder,
@Value("${osiam.tempLock.count:0}") Integer maxLoginFailures,
@Value("${osiam.tempLock.timeout:0}") Integer lockTimeout) {
this.userProvisioning = userProvisioning;
this.shaPasswordEncoder = shaPasswordEncoder;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
this.maxLoginFailures = maxLoginFailures;
this.lockTimeout = lockTimeout;
}
/**
* 注册auth User
*
* @param user AuthUser
* @return string
*/
public String register(AuthUser user) {
String username = user.getUsername();
if (this.findByUserName(username) != null) {
return "用户已存在";
}
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
String rawPassword = user.getPassword();
user.setPassword(encoder.encode(rawPassword));
List<String> roles = new ArrayList<>();
roles.add("ROLE_USER");
authMapper.register(user);
return "注册成功";
}
@BeforeAll
public static void setup() {
MonitoringHelper.initMocks();
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(10);
UserDetailsService userDetailsService = new InMemoryUserDetailsService(encoder);
AuthenticationService authenticationService = mock(AuthenticationService.class);
dummyAuthenticationProvider = new DummyAuthenticationProvider(encoder, userDetailsService, authenticationService);
}
@Override
protected void configure(AuthenticationManagerBuilder builder) throws Exception {
builder.jdbcAuthentication()
.passwordEncoder(new BCryptPasswordEncoder())
.dataSource(dataSource)
.usersByUsernameQuery("select name, password, enabled from t_account where name=?")
.authoritiesByUsernameQuery("select name, role from t_account_role where name=?");
}
@Test
public void encodingBCrypt() {
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//加密时使用
String hashPassword = passwordEncoder.encode("12345");
log.info("BCrypt HashPassword: {}", hashPassword);
}
public CrustAuthenticationProvider(CrustProperties props, BCryptPasswordEncoder passwordEncoder) {
this.props = props;
// 设置BCrypt密码加密器
if (props.isUseBcrypt() && passwordEncoder != null) {
setPasswordEncoder(passwordEncoder);
}
}
public WebSecurityConfig(BCryptPasswordEncoder bCryptPasswordEncoder,
CustomizeAuthenticationSuccessHandler customizeAuthenticationSuccessHandler,
CustomUserDetailsServiceImpl customUserDetailsServiceImpl) {
super();
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
this.customizeAuthenticationSuccessHandler = customizeAuthenticationSuccessHandler;
this.customUserDetailsServiceImpl = customUserDetailsServiceImpl;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.jdbcAuthentication()
.dataSource(this.dataSource)
.passwordEncoder(new BCryptPasswordEncoder());
}
@Test
void ChangePasswordSuccessfully() throws Exception {
UserEntity testUser = new UserEntity();
testUser.setUsername("username");
testUser.setPassword(PasswordUtil.hash("password1"));
testUser = userRepository.save(testUser);
RefreshTokenEntity refreshToken = new RefreshTokenEntity();
refreshToken.setToken(
tokenService.generateRefreshToken(testUser.getId(), testUser.getUsername()));
refreshToken.setUser(testUser);
refreshTokenRepository.save(refreshToken);
ChangePasswordCommand command =
new ChangePasswordCommand(refreshToken.getToken(), "newPassword1");
mvc()
.perform(
post("/api/user/password/change")
.content(toJson(command))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(documentPasswordChange());
Assertions.assertTrue(
new BCryptPasswordEncoder()
.matches(
"newPassword1", userRepository.findById(testUser.getId()).get().getPassword()));
}
@ParamValid
@Transactional
public void modifyLoginPwd(ModifyLoginPwdParam param) {
UserAccount userAccount = userAccountRepo.getOne(param.getUserAccountId());
BCryptPasswordEncoder pwdEncoder = new BCryptPasswordEncoder();
if (!pwdEncoder.matches(param.getOldLoginPwd(), userAccount.getLoginPwd())) {
throw new BizException(BizError.旧的登录密码不正确);
}
modifyLoginPwd(param.getUserAccountId(), param.getNewLoginPwd());
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("test1")
.secret(new BCryptPasswordEncoder().encode("test1111"))
.authorizedGrantTypes("password", "refresh_token")
.accessTokenValiditySeconds(3600)
.refreshTokenValiditySeconds(864000)
.scopes("all", "a", "b", "c")
.and()
.withClient("test2")
.secret(new BCryptPasswordEncoder().encode("test2222"))
.accessTokenValiditySeconds(7200);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BCryptPasswordEncoder pe=new BCryptPasswordEncoder();
//String c="$e0801$7Holo9EgzBeg5xf/WLZu3/5IQwOyEPDLJPgMXkF9jnekBrbQUMt4CF9O2trkz3zBCnCLpUMR437q/AjQ5TTToA==$oYB8KRSxAsxkKkt5r79W6r6P0wTUcKwGye1ivXRN0Ts="
//;
System.out.println(pe.encode("admin"));
// System.out.println(pe.encode("shimingxy")+"_password");
//System.out.println(pe.matches("shimingxy"+"_password", c));
}
/**
* 账号注册
*
* @param param
*/
@ParamValid
@Transactional
public void register(UserAccountRegisterParam param) {
UserAccount userAccount = userAccountRepo.findByUserName(param.getUserName());
if (userAccount != null) {
throw new BizException(BizError.用户名已存在);
}
param.setLoginPwd(new BCryptPasswordEncoder().encode(param.getLoginPwd()));
param.setMoneyPwd(new BCryptPasswordEncoder().encode(param.getMoneyPwd()));
UserAccount newUserAccount = param.convertToPo();
RegisterSetting setting = registerSettingRepo.findTopByOrderByLatelyUpdateTime();
if (!setting.getRegisterEnabled()) {
throw new BizException(BizError.未开放注册功能);
}
if (setting.getInviteRegisterEnabled()) {
InviteCode inviteCode = inviteCodeRepo
.findTopByCodeAndPeriodOfValidityGreaterThanEqual(param.getInviteCode(), new Date());
if (inviteCode == null) {
throw new BizException(BizError.邀请码不存在或已失效);
}
newUserAccount.updateInviteInfo(inviteCode);
} else {
newUserAccount.setRebate(setting.getRegitserDefaultRebate());
}
userAccountRepo.save(newUserAccount);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* BCryptPasswordEncoder password encoder
* @return
*/
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder(4);
}
public static String encode(String password) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(4);
String encodedPassword = encoder.encode(password);
return encodedPassword;
}
public static String encode(String password) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder.encode(password);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(Service()).passwordEncoder(new BCryptPasswordEncoder() {
});
}
@Bean
public PasswordEncoder loadPasswordEncoder() {
return new BCryptPasswordEncoder();
}