Spring-Boot登录无需使用Spring Security

huangapple go评论63阅读模式
英文:

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(&quot;name&quot;)
public class MainController {
@Autowired
private AccountRepository accountRepo;
public MainController(AccountRepository accountRepo) {
this.accountRepo = accountRepo;
}
@RequestMapping(value=&quot;/registration&quot;, method = RequestMethod.POST)
public String registerAccount(@ModelAttribute(&quot;accountForm&quot;) AccountEntity accountForm, BindingResult bindingResult, Model model){
if (bindingResult.hasErrors()) {
return &quot;error&quot;;
}
//Grabs information from view and saves them to attribute to save to database
model.addAttribute(&quot;userName&quot;, accountForm.getUserName());
model.addAttribute(&quot;email&quot;, accountForm.getEmail());
model.addAttribute(&quot;firstName&quot;, accountForm.getFirstName());
model.addAttribute(&quot;lastName&quot;, accountForm.getLastName());
model.addAttribute(&quot;password&quot;, accountForm.getPassword());
model.addAttribute(&quot;age&quot;, accountForm.getAge());
//model.addAttribute(&quot;gender&quot;, 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(&quot;the email or username already exists&quot;);
return &quot;redirect:registration&quot;;
}
else{
accountRepo.save(accountForm);
return &quot;redirect:login&quot;;
}
}
@RequestMapping(value=&quot;/login&quot;, method = RequestMethod.GET)
public String showLoginPage(ModelMap model){
model.addAttribute(&quot;login&quot;, new AccountEntity());
return &quot;login&quot;;
}
@RequestMapping(value=&quot;/login&quot;, method = RequestMethod.POST)
public String submitLoginIn(@ModelAttribute(&quot;login&quot;) AccountEntity account){
AccountEntity accountFormEmail = accountRepo.findByEmail(account.getEmail());
AccountEntity accountFormPassword = accountRepo.findByPassword(account.getPassword());
// Can&#39;t login if passwords are the same as an existing account --&gt; need to fix
if(accountFormEmail == null || accountFormPassword == null)
{
System.out.print(&quot;Account does not exist&quot;);
return &quot;redirect:login&quot;;
}
else {
System.out.print(&quot;account exist&quot;);
return &quot;redirect:welcome&quot;; //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 = &quot;user&quot;)
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


&lt;%@ page import=&quot;java.net.URLDecoder&quot; %&gt;
&lt;%@ taglib prefix=&quot;form&quot; uri=&quot;http://www.springframework.org/tags/form&quot; %&gt;
&lt;html&gt;
&lt;head&gt;
&lt;!-- Required MetaFiles --&gt;
&lt;meta name=&quot;content-type&quot; content=&quot;text-html&quot; charset=&quot;utf-8&quot;&gt;
&lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1, shrink-to-fit=no&quot;&gt;
&lt;meta name=&quot;keywords&quot; content=&quot;keyword1, keyword2, keyword3&quot;&gt;
&lt;meta name=&quot;description&quot; content=&quot;this is my page&quot;&gt;
&lt;!-- Webjars for Bootstrap and Jquery --&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css&quot; integrity=&quot;sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T&quot; crossorigin=&quot;anonymous&quot;&gt;
&lt;script src=&quot;https://code.jquery.com/jquery-3.3.1.slim.min.js&quot; integrity=&quot;sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js&quot; integrity=&quot;sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js&quot; integrity=&quot;sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM&quot; crossorigin=&quot;anonymous&quot;&gt;&lt;/script&gt;
&lt;style&gt;&lt;%@include file=&quot;/WEB-INF/css/login.css&quot;%&gt;&lt;/style&gt;
&lt;title&gt;Login&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;%--@elvariable id=&quot;login&quot; type=&quot;&quot;--%&gt;
&lt;form:form modelAttribute=&quot;login&quot; &gt;
&lt;div class=&quot;form-group container&quot; id=&quot;positionOfLogin&quot; style=&quot;text-align: center&quot;&gt;
&lt;div&gt;
&lt;form:input type=&quot;email&quot;
class=&quot;form-control MyInput&quot;
id=&quot;email&quot;
style=&quot;display: inline; width: 300px;&quot;
placeholder=&quot;email@example.com&quot;
path=&quot;email&quot;/&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;form:input type=&quot;password&quot;
name=&quot;password&quot;
class=&quot;form-control MyInput&quot;
id=&quot;password&quot;
placeholder=&quot;password&quot;
path=&quot;password&quot;/&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;form:button type=&quot;submit&quot; style=&quot;text-align: center&quot; class=&quot;form-control MyButton&quot;&gt;Login&lt;/form:button&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;a href=&quot;/registration&quot;
type=&quot;submit&quot; class=&quot;form-control MyButton&quot; &gt;Sign Up&lt;/a&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/form:form&gt;
&lt;/body&gt;
&lt;/html&gt;```
</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>

huangapple
  • 本文由 发表于 2020年10月1日 02:49:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/64143958.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定