英文:
Spring-Boot Login without Spring Security
问题
@Controller
@SessionAttributes("name")
public class MainController {
@Autowired
private AccountRepository accountRepo;
public MainController(AccountRepository accountRepo) {
this.accountRepo = accountRepo;
}
@RequestMapping(value="/registration", method = RequestMethod.POST)
public String registerAccount(@ModelAttribute("accountForm") AccountEntity accountForm, BindingResult bindingResult, Model model){
if (bindingResult.hasErrors()) {
return "error";
}
// Grabs information from view and saves them to attribute to save to database
model.addAttribute("userName", accountForm.getUserName());
model.addAttribute("email", accountForm.getEmail());
model.addAttribute("firstName", accountForm.getFirstName());
model.addAttribute("lastName", accountForm.getLastName());
model.addAttribute("password", accountForm.getPassword());
model.addAttribute("age", accountForm.getAge());
// Email Verification
String randomVerificationCode = RandomString.make(64);
accountForm.setVerificationCode(randomVerificationCode);
AccountEntity emailChecker = accountRepo.findByEmail(accountForm.getEmail());
AccountEntity usernameChecker = accountRepo.findByUserName(accountForm.getUserName());
// Checks if an email and username are unique;
// If email or username already exists in database, throws error
if(emailChecker != null || usernameChecker != null){
System.out.println("the email or username already exists");
return "redirect:registration";
}
else{
accountRepo.save(accountForm);
return "redirect:login";
}
}
@RequestMapping(value="/login", method = RequestMethod.GET)
public String showLoginPage(ModelMap model){
model.addAttribute("login", new AccountEntity());
return "login";
}
@RequestMapping(value="/login", method = RequestMethod.POST)
public String submitLoginIn(@ModelAttribute("login") AccountEntity account){
AccountEntity accountFormEmail = accountRepo.findByEmail(account.getEmail());
AccountEntity accountFormPassword = accountRepo.findByPassword(account.getPassword());
// Can't login if passwords are the same as an existing account --> need to fix
if(accountFormEmail == null || accountFormPassword == null) {
System.out.print("Account does not exist");
return "redirect:login";
}
else {
System.out.print("account exist");
return "redirect:welcome"; //Change later
}
}
}
package com.CSCI4050.TermProject.CovidWebsite.entities;
import javax.persistence.*;
@Entity(name = "user")
public class AccountEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String userName;
private String email;
private String password;
private Integer age;
private String verificationCode;
// Getters and Setters...
}
<%@ page import="java.net.URLDecoder" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<!-- Required MetaFiles -->
<meta name="content-type" content="text-html" charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="keywords" content="keyword1, keyword2, keyword3">
<meta name="description" content="this is my page">
<!-- Webjars for Bootstrap and Jquery -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<style><%@include file="/WEB-INF/css/login.css"%></style>
<title>Login</title>
</head>
<body>
<form:form modelAttribute="login">
<div class="form-group container" id="positionOfLogin" style="text-align: center">
<div>
<form:input type="email" class="form-control MyInput" id="email" style="display: inline; width: 300px;" placeholder="email@example.com" path="email"/>
</div>
<div>
<form:input type="password" name="password" class="form-control MyInput" id="password" placeholder="password" path="password"/>
</div>
<div>
<form:button type="submit" style="text-align: center" class="form-control MyButton">Login</form:button>
</div>
<div>
<a href="/registration" type="submit" class="form-control MyButton">Sign Up</a>
</div>
</div>
</form:form>
</body>
</html>
英文:
I currently have an application that has a working login and registration page. Everything was going smoothly and all test cases were working until I got to a scenario where the password required a unique one. It would throw an error if a user logged in with a password that was the same as an existing one. Could someone lead me in the right direction to figure this bug out? I would assume it would be something in the controller but I am not 100% sure. I am also using the built in h2 memory database.
EDIT: I also just tested another use case, I am not checking if the associated email put in has the correct password, I am only checking if the data put in are in the database.
This is the Main Controller
@Controller
@SessionAttributes("name")
public class MainController {
@Autowired
private AccountRepository accountRepo;
public MainController(AccountRepository accountRepo) {
this.accountRepo = accountRepo;
}
@RequestMapping(value="/registration", method = RequestMethod.POST)
public String registerAccount(@ModelAttribute("accountForm") AccountEntity accountForm, BindingResult bindingResult, Model model){
if (bindingResult.hasErrors()) {
return "error";
}
//Grabs information from view and saves them to attribute to save to database
model.addAttribute("userName", accountForm.getUserName());
model.addAttribute("email", accountForm.getEmail());
model.addAttribute("firstName", accountForm.getFirstName());
model.addAttribute("lastName", accountForm.getLastName());
model.addAttribute("password", accountForm.getPassword());
model.addAttribute("age", accountForm.getAge());
//model.addAttribute("gender", accountForm.getGender());
//Email Verification
String randomVerificationCode = RandomString.make(64);
accountForm.setVerificationCode(randomVerificationCode);
AccountEntity emailChecker = accountRepo.findByEmail(accountForm.getEmail());
AccountEntity usernameChecker = accountRepo.findByUserName(accountForm.getUserName());
//checks if an email and username are unique;
//if email or username already exists in database, throws error
if(emailChecker != null || usernameChecker != null){
System.out.println("the email or username already exists");
return "redirect:registration";
}
else{
accountRepo.save(accountForm);
return "redirect:login";
}
}
@RequestMapping(value="/login", method = RequestMethod.GET)
public String showLoginPage(ModelMap model){
model.addAttribute("login", new AccountEntity());
return "login";
}
@RequestMapping(value="/login", method = RequestMethod.POST)
public String submitLoginIn(@ModelAttribute("login") AccountEntity account){
AccountEntity accountFormEmail = accountRepo.findByEmail(account.getEmail());
AccountEntity accountFormPassword = accountRepo.findByPassword(account.getPassword());
// Can't login if passwords are the same as an existing account --> need to fix
if(accountFormEmail == null || accountFormPassword == null)
{
System.out.print("Account does not exist");
return "redirect:login";
}
else {
System.out.print("account exist");
return "redirect:welcome"; //Change later
}
}
}
This is the AccountEntity
package com.CSCI4050.TermProject.CovidWebsite.entities;
import javax.management.relation.Role;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import java.util.Set;
@Entity (name = "user")
public class AccountEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;
private String userName;
private String email;
private String password;
//private String gender;
private Integer age;
private String verificationCode;
//Getters and Setters
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/*
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
*/
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getVerificationCode() {
return verificationCode;
}
public void setVerificationCode(String verificationCode) {
this.verificationCode = verificationCode;
}
}
This is the login.jsp
<%@ page import="java.net.URLDecoder" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<!-- Required MetaFiles -->
<meta name="content-type" content="text-html" charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="keywords" content="keyword1, keyword2, keyword3">
<meta name="description" content="this is my page">
<!-- Webjars for Bootstrap and Jquery -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<style><%@include file="/WEB-INF/css/login.css"%></style>
<title>Login</title>
</head>
<body>
<%--@elvariable id="login" type=""--%>
<form:form modelAttribute="login" >
<div class="form-group container" id="positionOfLogin" style="text-align: center">
<div>
<form:input type="email"
class="form-control MyInput"
id="email"
style="display: inline; width: 300px;"
placeholder="email@example.com"
path="email"/>
</div>
<div>
<form:input type="password"
name="password"
class="form-control MyInput"
id="password"
placeholder="password"
path="password"/>
</div>
<div>
<form:button type="submit" style="text-align: center" class="form-control MyButton">Login</form:button>
</div>
<div>
<a href="/registration"
type="submit" class="form-control MyButton" >Sign Up</a>
</div>
</div>
</form:form>
</body>
</html>```
</details>
# 答案1
**得分**: 0
如果您的密码是以明文保存的,目前的逻辑是可以的。但安全级别太低了。我建议您使用MD5对密码进行编码,然后再保存到数据库中。同样的字符串经过MD5编码会得到相同的结果。这样您就可以避免在数据库中保存明文密码。
目前MD5编码器并不安全,因为有更多的在线解码方式。您应该很好地保护数据库。建议定期提示用户更改密码,这是一个不错的方法。
<details>
<summary>英文:</summary>
If your password is saved with plain, current logic is ok. But security level is too low. I suggest you encode password with MD5 then save to DB. The same string encoded with MD5 has same result. So you can avoid save plain password in DB.
The MD5 encoder is not safety currently because there are more decoder way online. You should protect DB well. It is a good way to suggest user change password in period.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论