0

Проблема: Не открывается форма регистрации в приложении Spring Boot + Spring Security на heroku.

На локальной машине все ок.

В чём проблема понять не могу:

Вот основной код:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
@ComponentScan("com.github.owgrant24.springbootone")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private UserDetailsService userDetailsService;

    @Autowired
    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    // Правила (ограничения прав)
   protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            // Указываем URL которые будут доступны только анонимным (неавторизованным) пользователям
            .antMatchers("/sign_up", "/login").anonymous()
            // Указываем URL которые будут доступны только авторизованным пользователям
            .antMatchers("/cars/**").authenticated()
            .antMatchers("/static/**", "/webjars/**").permitAll()
            .and()
            .formLogin()
            // Указываем где у нас форма логина
            .loginPage("/login")
            .loginProcessingUrl("/login/process")
            // задаем что будет будет в качестве username
            .usernameParameter("email")
            // задаем что будет будет в качестве password в форме (по умолчанию - password)
            .passwordParameter("password")
            // При неудачной авторизации сюда будет редирект
            .failureUrl("/login?error=true")
            // Когда пользователь прошёл аутентификацию и хочет зайти на странички для не авторизированных
            // пользователей
            .and().exceptionHandling().accessDeniedPage("/cars")
            .and()
            // добавлена возможность logout
            .logout();
}

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

    @Bean
    protected AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        return daoAuthenticationProvider;
    }

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

Вот контроллер, который отвечает за авторизацию и аутентификацию

@Controller
public class AuthController {
    private UserService userService;
    private UserValidator userValidator;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setUserValidator(UserValidator userValidator) {
        this.userValidator = userValidator;
    }

    @GetMapping("/")
    public String home() {
        return "redirect:/cars";
    }

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

    @PostMapping("/sign_up")
    public String signUp(@ModelAttribute("user") @Valid User user, BindingResult result) {
        userValidator.validate(user, result);
        if (result.hasErrors()) {
            return "/auth/sign_up";
        }
        userService.saveUser(user);
        return "redirect:/login";
    }

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

}

Вот ссылка на мой проект, вдруг я не все указал, может проблема не в этом... https://github.com/owgrant24/ExampleProject/tree/master/SpringBootOne

0

1 ответ 1

0

Ошибка закралась тут :

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

@PostMapping("/sign_up")
public String signUp(@ModelAttribute("user") @Valid User user, BindingResult result) {
    userValidator.validate(user, result);
    if (result.hasErrors()) {
        return "auth/sign_up";
    }
    userService.saveUser(user);
    return "redirect:/login";
}

было

return "/auth/sign_up";

стало

return "auth/sign_up";

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.