Home > Blockchain >  Interacting with html file from controller using Thymeleaf
Interacting with html file from controller using Thymeleaf

Time:06-01

I am currently trying to create a controller to interact with an html file using Thymeleaf. After a while I noticed that perhaps my controller (more specifically the @PostMapping) isn't interacting with my html page at all. The reason I thought this is because no matter what input I placed as email/password (be it correct or incorrect) it would always link me to (/login?error). I tested out a simple conditional that would print "HERE" on the html page once the Post request is called to see if that was truly the case. The print never occurs. The point of this post is to understand why this simple post request is being ignored. Since I a making a simple Post request, I would assume that the "Here" would get printed no matter what.

My html code

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="ISO-8859-1">
    <title>Login Page</title>
</head>
<body>
    <form th:action="@{/login}" th:object="${user}" method="post">
        
        <div th:if="${here}">
            <p>HERE</p>
        </div>
        
        <div>
            <label>Email</label>
            <input type="text" th:field="*{email}">
        </div>
    
        <div>
            <label>Password</label>
            <input type="text" th:field="*{password}" placeholder="Password">
        </div>
        
        <input type="submit" value="submit"/>
    </form>
</body>
</html>

My Controller class

@Controller
public class UserController {
    
    UserRepository userRepo;
    UserService userService;
    
    @GetMapping("/login")
    public String login(Model model) {
        model.addAttribute("user", new User());
        return "login";
    }
    
    @PostMapping("/login")
    public String loginUser(@ModelAttribute("user") User user, Model model) {
        model.addAttribute("here", true);

        return "login";
    }
}

My Spring Security Configurations

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    private final UserService userService;
    private final BCryptPasswordEncoder passwordEncoder;
    
    public WebSecurityConfig(UserService userService, BCryptPasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }
    
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeHttpRequests()
                .antMatchers("/registration/**", "/login")
                .permitAll()
                .anyRequest()
                .authenticated().and()
                .formLogin().loginPage("/login").permitAll();;
        
        return http.build();
    }

    
    protected void configure(AuthenticationManagerBuilder auth) throws Exception{
        
    }
    
    @Bean
    public DaoAuthenticationProvider daoAutenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder(passwordEncoder);
        provider.setUserDetailsService(userService);
        return provider;
    }
}

CodePudding user response:

To be honest I am not sure what I did differently, but I managed to get it to work finally.

CodePudding user response:

you need to add additional configuration to inform which fields will be validated, because by default spring-security validates username and password, in your case, you are using email, try the following:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .csrf().disable()
        .authorizeHttpRequests()
            .antMatchers("/registration/**", "/login")
            .permitAll()
            .anyRequest()
            .authenticated().and()
            .formLogin()
            .loginPage("/login")
            .usernameParameter("email")
            .passwordParameter("password")
            .permitAll();
    
    return http.build();
}

you can see one of my examples at: https://github.com/Rafael472/WebControl/blob/main/src/main/java/com/SystemsSolutions/WebControl/security/config/SecurityConfig.java

for the access denied message, you can use the following configuration:

.exceptionHandling()
.accessDeniedPage("/access-denied");

and map '/access-denied' to return your custom messages an example is:

@RequestMapping("/access-denied")
public ModelAndView accessDenied(HttpServletResponse resp) {
if (UserService.getUserAuthenticated().getVerificado() == 0) {
ModelAndView mv = new ModelAndView("redirect:/login?unconfirmed-email");
return mv;
}

ModelAndView mv = new ModelAndView("user/Access-denied");
mv.addObject("status", resp.getStatus());
mv.addObject("error", "Access Denied");
mv.addObject("message", "you do not have permission to access this area or action.");
return mv;
}
  • Related