Страница входа в Spring Security и регистрация пользователя в одном файле html - PullRequest
1 голос
/ 06 марта 2020

Я немного новичок в Spring и в настоящее время пытаюсь создать веб-приложение, которое включает вход в систему пользователя с защитой весенней загрузки. Первоначальная аутентификация при входе в систему работала, когда у меня была страница входа в систему и я создал страницу пользователя в виде двух отдельных HTML файлов. Сейчас я пытаюсь создать одну веб-страницу, используя javascript. Однако я больше не могу получить доступ к страницам.

Это мой пользователь Entity

package com.fncd.model;

import java.util.Collection;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;

import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name="fncd_users", uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class Users {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long user_id;
    private String first_name;
    private String last_name;
    private String email;
    private String password;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinTable(
            name = "users_roles",
            joinColumns = @JoinColumn(
                    name = "user_id", referencedColumnName = "user_id"),
            inverseJoinColumns = @JoinColumn(
                    name = "role_id", referencedColumnName = "id"))
    private Collection<Role> roles;

    public Users() {
    }

    public Users(String first_name, String last_name, String email, String password) {
        this.first_name = first_name;
        this.last_name = last_name;
        this.email = email;
        this.password = password;
    }

    public Users(String first_name, String last_name, String email, String password,
            Collection<Role> roles) {
        this.first_name = first_name;
        this.last_name = last_name;
        this.email = email;
        this.password = password;
        this.roles = roles;
    }

    @Override
    public String toString() {
        return "Users {" + 
               "user_id=" + user_id + 
               ", first_name=" + first_name + 
               ", last_name=" + last_name + 
               ", email=" + email + 
               ", password=" + password + 
               ", roles=" + roles + "}";
    }

    public Collection<Role> getRoles() {
        return roles;
    }

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

    public Long getUser_id() {
        return user_id;
    }

    public void setUser_id(Long user_id) {
        this.user_id = user_id;
    }

    public String getFirst_name() {
        return first_name;
    }


    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    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;
    }

}

Это моя конфигурация безопасности

package com.fncd.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.fncd.service.UserServiceSec;

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserServiceSec userService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login**", "/js/**", "/css/**", "/imgs/**", "/webjars/**", "/views/**")
                .permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").defaultSuccessUrl("/dashboard", true).permitAll().and().logout()
                .invalidateHttpSession(true).clearAuthentication(true)
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login?logout")
                .permitAll();
    }

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

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider auth = new DaoAuthenticationProvider();
        auth.setUserDetailsService(userService);
        auth.setPasswordEncoder(passwordEncoder());
        return auth;
    }

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

}

Контроллер моего приложения

package com.fncd.controller;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.support.RequestContextUtils;

@Controller
public class AppController {

    @RequestMapping("/login")
    public String login(Model m) {
        return "login";
    }

    @GetMapping("/user")
    public String userIndex() {
        return "user/dashboard";
    }

    @RequestMapping("/dashboard")
    public String dashboard() {
        return "dashboard";
    }

    @RequestMapping("/dashboard_2")
    public String dashboard_2() {
        return "dashboard_2";
    }

    @RequestMapping("/header")
    public String header() {
        return "header";
    }

    @RequestMapping("/footer")
    public String footer() {
        return "footer";
    }

    @RequestMapping("/annual_report")
    public String report_overview() {
        return "annual_report";
    }

    @RequestMapping("/settings")
    public String settings() {
        return "settings";
    }

    @RequestMapping("/change_pw")
    public String change_pw() {
        return "change_pw";
    }

    @RequestMapping("/forgot_pw")
    public String forgot_pw() {
        return "forgot_pw";
    }

    @RequestMapping("/forgot_pw_1")
    public String forgot_pw_1() {
        return "forgot_pw_1";
    }

    @RequestMapping("/forgot_pw_2")
    public String forgot_pw_2() {
        return "forgot_pw_2";
    }

    @RequestMapping("/success")
    public String getSuccess(HttpServletRequest request) {
        Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request);
        if (inputFlashMap != null) {
            return "success";
        } else {
            return "redirect:/dashboard"; // if user refresh success page
        }
    }

    @RequestMapping("/fail")
    public String getError(HttpServletRequest request) {
        Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request);
        if (inputFlashMap != null) {
            return "fail";
        } else {
            return "redirect:/dashboard"; // if user refresh success page
        }
    }
}

Контроллер регистрации пользователя

package com.fncd.controller;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fncd.model.Users;
import com.fncd.registrationdto.UserRegistrationDto;
import com.fncd.service.UserServiceSec;

@Controller
@RequestMapping("/create_user")
public class UserRegistrationController {

    @Autowired
    private UserServiceSec userServiceSec;

    @ModelAttribute("user")
    public UserRegistrationDto userRegistrationDto() {
        return new UserRegistrationDto();
    }

    @GetMapping
    public String showCreateUserPage(Model m) {
        return "login";
    }

    @PostMapping
    public String createUserAccount(@ModelAttribute("user")@Valid UserRegistrationDto userRegistrationDto, 
            BindingResult result) {
        Users existing = userServiceSec.findByEmail(userRegistrationDto.getEmail());
        if(existing != null) 
            result.rejectValue("email", null, "There is already an account registered with that email");
        if(result.hasErrors())
            return "create_user";

            userServiceSec.save(userRegistrationDto);

            return "redirect:/?success";        
    }
}

логин. html

image

Это ошибка, которую я получаю:

Причина: java .lang.IllegalStateException: Ни BindingResult, ни простой целевой объект для имени компонента «пользователь» не доступны в качестве атрибута запроса на org.springframework.web.servlet.support.BindStatus. (BindStatus. java: 153) ~ [spring-web mvc -5.2.3 .RELEASE.jar: 5.2.3.RELEASE] at org.springframework.web.servlet.support.RequestContext.getBindStatus (RequestContext. java: 903) ~ [spring-web mvc -5.2.3.RELEASE.jar : 5.2.3.RELEASE] at org.thymeleaf.spring5.context.web mvc .SpringWebMvcThymeleafRequestContext.getBindStatus (SpringWebMvcThymeleafRequestContext. java: 227) ~ [thymeleafjel. .RELEASE] at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression (FieldUtils. java: 306) ~ [t hymeleaf-spring5-3.0.11.RELEASE.jar: 3.0.11.RELEASE] at org.thymeleaf.spring5.util.FieldUtils.getBindStatus (FieldUtils. java: 253) ~ [thymeleaf-spring5-3.0.11.RELEASE .jar: 3.0.11.RELEASE] at org.thymeleaf.spring5.util.FieldUtils.getBindStatus (FieldUtils. java: 227) ~ [thymeleaf-spring5-3.0.11.RELEASE.jar: 3.0.11.RELEASE] в org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess (AbstractSpringFieldTagProcessor. java: 174) ~ [thymeleaf-spring5-3.0.11.RELEASE.jar: 3.0.11.RELEASE] в org.thymeleement.pro. AbstractAttributeTagProcessor.doProcess (AbstractAttributeTagProcessor. java: 74) ~ [thymeleaf-3.0.11.RELEASE.jar: 3.0.11.RELEASE] ... пропущено 88 общих кадров

Любая помощь будет с благодарностью Заранее спасибо!

...