自定义Spring Boot登录表单

时间:2019-12-16 08:32:28

标签: java spring-boot spring-security

我正在尝试为Spring启动创建自己的自定义登录页面。我刚收到“ http://localhost:8080/login?error”,仅此而已。无法在控制台中调试任何内容。完全没有信息。我究竟做错了什么?我是Spring Boot和Java的新手。

login.html

<div id="login-form-wrapper">
<form id="login-form" action="/login"  method="post">
    <div class="form-group">
        <label for="username">Email address</label>
        <input type="email" name="username" id="username" class="form-control"
               aria-describedby="emailHelp" autofocus required/>
        <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
    </div>
    <div class="form-group">
        <label for="password">Password</label>
        <input type="password" name="password" class="form-control" id="password" required/>
    </div>
    <button type="submit" class="btn btn-primary">Login</button>
    <div id="no-account-wrapper">
        <small>Don't have an account?<a href="/registration"> Sign up</a></small>
    </div>
</form>

控制器

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String showLoginForm() {
    return "login";
}

SecurityConfig

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    final
    UserDetailsService userDetailsService;

    @Autowired
    public SecurityConfig(@Qualifier("myUserDetailsService") UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Bean
    public DaoAuthenticationProvider authProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(bCryptPasswordEncoder());
        return authProvider;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests().antMatchers("/resources/**", "/css/**", "/registration", "/").permitAll()
                .anyRequest().authenticated()
        .and().formLogin()
        .loginPage("/login")
                .usernameParameter("email")
                .passwordParameter("password")
        .successForwardUrl("/profile")
        .permitAll();

    }

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

我对注解@Configuration和@ComponentScan不太确定

编辑:

添加了registration.html和注册控制器。从SecurityConfig中删除了@ComponentScan

registration.html

<div id="registration-form-wrapper">
<form id="registration-form" th:action="@{'/perform_registration'}" th:object="${user}" method="post">
    <div class="form-group">
        <label for="first-name">First Name</label>
        <input type="text" class="form-control" th:field="*{firstName}" id="first-name" required autofocus/>
    </div>
    <div class="form-group">
        <label for="last-name">Last Name</label>
        <input type="text" class="form-control" th:field="*{lastName}" id="last-name" required/>
    </div>
    <div class="form-group">
        <label for="email">Email address</label>
        <input type="email" class="form-control" id="email" th:field="*{email}" aria-describedby="emailHelp"
               required/>
        <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
        <p class="alert alert-danger" th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></p>
    </div>
    <div class="form-group">
        <label for="password">Password</label>
        <input type="password" class="form-control" th:field="*{password}" id="password" minlength="8" required/>
    </div>
    <div class="form-group">
        <label for="passwordRepeat">Repeat password</label>
        <input type="password" class="form-control" th:field="*{matchingPassword}" id="passwordRepeat" minlength="8"
               required/>
    </div>
    <button type="submit" class="btn btn-primary">Sign up</button>
    <div id="no-account-wrapper">
        <small>Already have an account?<a href="login.html" th:href="@{'/'}"> Login</a></small>
    </div>
</form>

注册控制器

@RequestMapping(value = "/registration", method = RequestMethod.GET)
public String showRegistrationForm(WebRequest request, Model model) {
    UserDto userDto = new UserDto();
    model.addAttribute("user", userDto);
    return "registration";
}

@PostMapping(value = "/perform_registration", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String registerUserAccount(@ModelAttribute(name = "user") @Valid UserDto userDto, BindingResult result) {

    User existing = userRepository.findByEmail(userDto.getEmail());
    if (existing != null) {
        log.info("User with email {} already exists -> {}", userDto.getEmail(), existing);
        result.rejectValue("email", "required", "User with email " + userDto.getEmail() + " already exists.");
    }

    if (result.hasErrors()) {
        return "registration";
    }

    User newUser = new User();
    newUser.setFirstName(userDto.getFirstName());
    newUser.setLastName(userDto.getLastName());
    newUser.setEmail(userDto.getEmail());
    newUser.setPassword(getPasswordEncoder.encode(userDto.getPassword()));
    userRepository.save(newUser);

    return "redirect:/login";
}

编辑2:

@Service
public class MyUserDetailsService implements UserDetailsService {

    final UserRepository userRepository;

    public MyUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        Optional<User> user = Optional.ofNullable(userRepository.findByEmail(email));
        user.orElseThrow(()-> new UsernameNotFoundException("Not found: " + email));

        return user.map(MyUserDetails::new).get();
    }
}

谢谢!

1 个答案:

答案 0 :(得分:1)

@Configuration“表明该类具有@Bean定义方法。因此Spring容器可以处理该类并生成要在应用程序中使用的Spring Bean。”查看更多here.

因为它有一些Bean,所以它是您的Security配置类所必需的。您不需要@ComponentScan

紧跟@Bean@Autowired中的explanation。您需要创建自定义UserDetailsService,该自定义@Bean @Override public UserDetailsService userDetailsService() { return new CustomCustomerDetailsService(); } @Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService()); authProvider.setPasswordEncoder(encoder()); return authProvider; } 必须已由您的用户实体(用于用户身份验证)实现为Bean,并已注入到DAO身份验证中。

@Service("customCustomerDetailsService")
public class CustomCustomerDetailsService implements UserDetailsService  {

    @Autowired
    private CustomerRepository customers;    




    @Override
    public UserDetails loadUserByUsername(String email)  {

      return this.customers.findByEmail(email)
            .orElseThrow(() -> new UsernameNotFoundException("Username: " + email + " not found"));



    }

}

请参见this answer,以了解如何实现自定义用户详细信息类。

完成自定义UserDetailsS​​ervice

FormArray
相关问题