Spring Security 关于控制器的问题未调用我的postmapping方法

hs1rzwqc  于 2021-09-30  发布在  Java
关注(0)|答案(1)|浏览(288)

我是spring security的新手,有一些问题。
我想知道为什么我的控制器中的adduser方法没有被调用。
以下是我的类:用户实体:

@javax.persistence.Entity
@Table(name = "users")
public class User implements Entity<Long>, UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Size(min=5, message = "Not less than 5 chars")
private String username;
@Size(min=5, message = "Not less than 5 chars")
private String password;
@Transient
private String confirmPassword;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "users_roles",
        joinColumns = @JoinColumn(name = "user_id"),
        inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;

public User() {
}

public User(Long id, String username, String password, String confirmPassword) {
    this.id = id;
    this.username = username;
    this.password = password;
    this.confirmPassword = confirmPassword;
}

public User(String username, String password, String confirmPassword) {
    this.username = username;
    this.password = password;
    this.confirmPassword = confirmPassword;
}

public void setUsername(String username) {
    this.username = username;
}

public void setPassword(String password) {
    this.password = password;
}

public String getConfirmPassword() {
    return confirmPassword;
}

public void setConfirmPassword(String confirmPassword) {
    this.confirmPassword = confirmPassword;
}

public Set<Role> getRoles() {
    return this.roles;
}

public void setRoles(Set<Role> roles) {
    this.roles = roles;
}

@Override
public Long getId() {
    return this.id;
}

@Override
public void setId(Long id) {
    this.id = id;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    return getRoles();
}

@Override
public String getPassword() {
    return this.password;
}

@Override
public String getUsername() {
    return this.username;
}

@Override
public boolean isAccountNonExpired() {
    return false;
}

@Override
public boolean isAccountNonLocked() {
    return false;
}

@Override
public boolean isCredentialsNonExpired() {
    return false;
}

@Override
public boolean isEnabled() {
    return false;
}

方法保存在my userservice类中:

public User save(User user) throws Exception {
    if (checkIfExist(user)){
        LOGGER.warn("User with such username already exists");
        return null;
    }
    roleService.saveRoles(user.getRoles());
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    return userRepository.save(user);
}

我的注册管理员:

@Controller
public class RegistrationController {
private final UserService userService;

public RegistrationController(UserService userService) {
    this.userService = userService;
}

@GetMapping("/registration")
public String registration(Model model){
    model.addAttribute("userForm", new User());
    return "account/registration";
}

@PostMapping("/registration")
public String addUser(@ModelAttribute("userForm") @Valid User userForm, BindingResult bindingResult,
                      Model model) throws Exception {
    System.out.println("addUser is called");

    System.out.println(userForm);
    if (bindingResult.hasErrors()) {
        return "account/registration";
    }
    if (!userForm.getPassword().equals(userForm.getConfirmPassword())){
        model.addAttribute("passwordError", "Passwords do not match");
        return "account/registration";
    }
    if (userService.save(userForm)==null){
        model.addAttribute("usernameError", "User already exists");
        return "account/registration";
    }
    return "redirect:/";
}

我的spring安全配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception{
        httpSecurity
                .csrf()
                .disable()
                .authorizeRequests()
                .antMatchers("/css/**", "/js/**", "/images/**").permitAll()
                .antMatchers("/registration").not().fullyAuthenticated()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/")
                .permitAll()
                .and()
                .logout()
                .permitAll()
                .logoutSuccessUrl("/");
    }

}

和我的注册页面视图:

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
  <link th:href="@{/css/main.css}" rel="stylesheet">
  <link rel="icon" type="image/png" sizes="16x16" href="images/favicons/favicon-16x16.png">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="main">
  <div class="container">
    <div class="row justify-content-md-center">
      <div class="col col-6">
        <div class="h1-wrapper px-3 py-3 pt-md-5 pb-md-4 mx-auto text-center">
          <form method="post" th:object="${userForm}" th:action="@{/registration/}">
            <div class="form-group row">
              <label for="userName" class="col-sm-4 col-form-label text-left">Username:</label>
              <div class="col-sm-8 mb-4">
                <input type="text" required="required" class="form-control" id="userName"
                       th:field="*{username}">
              </div>
              <label for="password" class="col-sm-4 col-form-label text-left">Password:</label>
              <div class="col-sm-8 mb-4">
                <input type="text" required="required" class="form-control" id="password"
                       th:field="*{password}">
              </div>
              <label for="confirmPassword" class="col-sm-4 col-form-label text-left">Confirm Password:</label>
              <div class="col-sm-8 mb-4">
                <input type="text" required="required" class="form-control" id="confirmPassword"
                       th:field="*{confirmPassword}">
              </div>
            </div>
            <button class="myButton btn btn-block" type="submit">Submit</button>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>

</body>
</html>

所以我的问题是,为什么在填写注册表后单击submit按钮时,我的usercontroller中的adduser方法没有被调用?虽然我在模板中写了th:action=“@{/registration/}”,但它将我重定向到http://localhost:8080/login. 可能是因为我的WebSecurity配置类中的设置?但如果它按预期工作,什么时候应该调用我的adduser方法并在db中实际创建一个新用户?我已经按照指南了解了Spring Security 是如何工作的,但我不理解这一部分。我很感激任何能解释我问题解决方法的答案或链接。

qmb5sa22

qmb5sa221#

试一试 antMatchers("/registration").permitAll()

相关问题