簡體   English   中英

授權嘗試后 Spring /login?error

[英]Spring /login?error after authorization attempt

我是春季靴子的新手。 創建我自己的網站。 登錄應用程序時出現問題。 我嘗試了不同的方法,我不明白問題是什么。 輸入 http 請求時,該請求出現 http://localhost:8088/login?error 並在表單中顯示Invalid email and password消息。 請求通過數據庫,一切都很好。我需要它在登錄后轉到主頁,這是我試圖做的。

用戶服務

@Service
public class UserServiceImpl implements UserService, UserDetailsService {

private final UserRepository userRepository;
private final PasswordConfig passwordConfig;
private final RoleRepository roleRepository;

@Autowired
public UserServiceImpl(UserRepository userRepository, PasswordConfig passwordConfig, 
RoleRepository roleRepository) {
   this.userRepository = userRepository;
   this.passwordConfig = passwordConfig;
   this.roleRepository = roleRepository;
}

@Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {

   final Optional<User> user = userRepository.findByEmail(email);
   if(user.isPresent()) {
       return user.get();
   }else {
       throw new UsernameNotFoundException(MessageFormat.format("User with email {0} not 
found",email));
    }
}

@Override
public List<User> findAll() {
    return userRepository.findAll();
}

public User findUserById(Long userId) {
    Optional<User> userFromDb = userRepository.findById(userId);
    return userFromDb.orElse(new User());
}

@Override
@Transactional
public boolean signUp(User user) {
    user.setPassword(passwordConfig.getPasswordEncoder().encode(user.getPassword()));
    user.setRoles(Collections.singleton(new Role(1L, "ROLE_USER")));
    userRepository.save(user);
    return true;
}

身份驗證控制器

@Controller
public class AuthenticationController {

private final UserServiceImpl userService;

@Autowired
public AuthenticationController(UserServiceImpl userService) {
    this.userService = userService;
}

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

@PostMapping ("/registration")
public String registerUser(@ModelAttribute("user") @Valid User user, BindingResult 
bindingResult) {
    if (bindingResult.hasErrors()) {
        return "registration";
    }
    userService.signUp(user);
    return "login";
}

@GetMapping("/login")
public String loginPage(){
      return "login";
}

@GetMapping("/logout")
public String logoutPage() throws Exception {
      return "redirect:/";
}

網絡安全配置

@Configuration
@EnableWebSecurity
@ComponentScan
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

private final UserServiceImpl userService;

private final PasswordConfig passwordConfig;

private final AuthenticationSuccessHandler authSuccessHandler;

@Autowired
public WebSecurityConfig(UserServiceImpl userService, PasswordConfig passwordConfig, 
AuthenticationSuccessHandler authSuccessHandler) {
    this.userService = userService;
    this.passwordConfig = passwordConfig;
    this.authSuccessHandler = authSuccessHandler;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userService).passwordEncoder(passwordConfig.getPasswordEncoder());
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userService)
            .passwordEncoder(passwordConfig.getPasswordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/user/**")
        .hasRole("USER")
        .antMatchers("/admin/**")
        .hasRole("ADMIN")
        .antMatchers("/**")
        .permitAll()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/")
        .permitAll()
        .and()
        .logout()
        .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
        .logoutSuccessUrl("/login")
        .permitAll();
    http.csrf().disable();
    http.headers().frameOptions().disable();
}

登錄.html

<html lang="en" xmlns:th="http://www.thymeleaf.org"
  xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<title>SMS - Вход</title>

<link rel="stylesheet" type="text/css" href="/static/css/home.css" 
th:href="@{/css/signup.css}">

</head>
<body>

<div sec:authorize="isAuthenticated()" class="container has-text-centered has-text-info">
<h1>already logged in!</h1>
</div>

<div sec:authorize="isAnonymous()" class="container">
<img th:src="@{/img/SMS.JPG}" class="logo" alt="">

<form action="/login" method="POST">

    <input class="input" type="email" placeholder="email" name="username" >
    <input class="input" type="password" placeholder="password" name="password" >
    <p th:if="${param.error}" class="has-text-danger">
        Invalid email and password.
    </p>

    <input type="checkbox" checked class="checkbox" id="terms-and-cond">
    <label for="terms-and-cond">agree to our <a href="">terms and conditions</a></label>
    <br>
        <input type="checkbox" class="checkbox" id="notification">
        <label for="notification">recieve upcoming offers and events mails</a></label>
    <br>
    <button type="submit" class="submit-btn">sign in</button>
</form>
<a href="/registration" class="link">registr</a>
<a href="/" class="link">index</a>
</div>
</body>
</html>

控制台中沒有錯誤,只有:

Hibernate: select user0_.user_id as user_id1_8_, user0_.create_time as create_t2_8_, 
user0_.email as email3_8_, user0_.first_name as first_na4_8_, user0_.last_name as 
last_nam5_8_, user0_.password as password6_8_, user0_.phone_number as phone_nu7_8_ from user 
user0_ where user0_.email=?

我解決了我的問題,它幫助我將字段 enabled = true、locked = false 添加到 User 實體類

@Builder.Default
private Boolean locked = false;

@Builder.Default
private Boolean enabled = true;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM