java - 如果块没有正确执行
问题描述
我有一个 java web 项目,我有一个方法可以在用户登录时验证用户。我已经做了一个密码加密服务来验证,而不是他的密码是否合法。
String email = request.getParameter("email");
String password = request.getParameter("password");
try {
byte[] salt = LogicFacade.getSalt(email);
byte[] attemptedPassword = LogicFacade.getEncryptedPassword(email);
if (LogicFacade.authenticate(password, attempted password, salt))
//Here salt is null, whenever I try to log in, with a wrong username or password
{
User user = null;
user = LogicFacade.login(email, password);
HttpSession session = request.getSession();
session.setAttribute("user", user);
session.setAttribute("role", user.getRole());
return user.getRole() + "page";
} else {
String errorMessage = "the username or password you have selected does not exist";
throw new LoginSampleException(errorMessage);
}
} catch (NoSuchAlgorithmException | InvalidKeySpecException | LoginSampleException ex ) {
String errorMessage = "We have an internal problem, but we are working as hard as possible, to solve it.";
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
throw new LoginSampleException(errorMessage);
}
}
}
每当我输入错误的用户名或密码时,它都会说 Salt-parameter must be non-null。
这是因为我有一种方法可以从 SQL 数据库中检索用户的 salt,然后返回 null。
这是我的身份验证方法:
public boolean authenticate(String attemptedPassword, byte[] encryptedPassword, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException, LoginSampleException {
// Encrypt the clear-text password using the same salt that was used to
// encrypt the original password
byte[] encryptedAttemptedPassword = getEncryptedPassword(attemptedPassword, salt);
// Authentication succeeds if encrypted password that the user entered
// is equal to the stored hash
return Arrays.equals(encryptedPassword, encryptedAttemptedPassword);
}
我的问题是为什么在不满足 if 条件后它不执行 else 块。每当我调试项目时,在我尝试挖掘方法后它直接进入线程类?
有没有可能它可以进入 else 块而不立即抛出 NullPointerException?
解决方案
将您的 if 条件更改为,
if (salt!=null && LogicFacade.authenticate(password, attempted password, salt)){
...if-block
} else {
...else-block
}
由于 salt null 表示您的数据库中不存在提供的电子邮件。
推荐阅读
- visual-studio-code - VSCode 键绑定:命令与命令 ID?
- javascript - 有没有办法访问/读取和修改 .swz 文件的内容?
- python - 在主函数中调用异步函数
- corda - 从 RPC 客户端 vaultTrackBy 检索错过的 Corda 事务
- php - 在php中将客户端日期时间存储到UTC
- python - 无法使用 pandas ExcelWriter 在 excel 文件中写入表格内容
- excel - 如何让excel运行一个由替代和连接组成的函数并计算数值
- python - 用适当的范围对序列数据进行分类
- python - 使用 open(),我如何判断我是否在文件的最后一行?
- salesforce - 如何修复 System.LimitException:带有电子邮件警报的工作流导致超出 Apex CPU 时间限制?