Search code examples
spring-mvcthymeleaf

thymeleaf form GEt url is called instead of POST


The issue is that my form is calling GET controller instead of POST one.

<form class="m-t" role="form" th:action="@{login}" th:object="${adminLogin}" method="post" autocomplete="off">
            <div th:if="${error}" class="alert alert-danger"><span th:text="${error}">Invalid username and password!!</span></div>
                <div th:if="${logout}" class="alert alert-success">
                <span th:text="${logout}">You have been logged out.</span></div>
                <div class="form-group">
                    <input type="text" class="form-control" th:field="*{ssoId}" th:placeholder="#{login.form.field.username.placeholder}" required=""></input>
                </div>
                <div class="form-group">
                    <input type="password" class="form-control" th:field="*{password}" th:placeholder="#{login.form.field.password.placeholder}" required=""></input>
                </div>
                <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
                <button type="submit" formmethod="post" class="btn btn-primary block full-width m-b" th:text="#{login.form.login.button.value}"></button>

                <a href="#"><small>Forgot password?</small></a>
            </form>

Here is my controller

@Controller
public class AdminController {

    private static final Logger LOGGER = LogManager.getLogger(AdminController.class);

    @Autowired
    FoodoutletUserSecurity userDetailsService;

    @Autowired
    private MessageSource messageSource;

    @RequestMapping(value = { "/login", "/" }, method = RequestMethod.GET)
    public ModelAndView login(Model model, @RequestParam(value = "error", required = false) String error,
            @RequestParam(value = "logout", required = false) String logout) {

        LOGGER.debug("login page");
        ModelAndView view = new ModelAndView("login", "command", model);
        //view.addObject("adminLogin", adminLogin);
        if (error != null) {
            view.addObject("error", "Invalid username and password!");
        }

        if (logout != null) {
            view.addObject("msg", "You've been logged out successfully.");
        }


        //view.setViewName("/login");

        return view;

    }

    @RequestMapping(value = { "/404" }, method = RequestMethod.GET)
    public ModelAndView error404(HttpServletRequest request) {
        LOGGER.debug("4 page");
        ModelAndView model = new ModelAndView();
        model.setViewName("404");
        return model;
    }

    @ModelAttribute("adminLogin")
    public AdminLogin createModel() {
        return new AdminLogin();
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(Model model, @Valid @ModelAttribute AdminLogin adminLogin, HttpServletRequest request,
            @RequestParam(value = "error", required = false) String error, @RequestParam(value = "logout", required = false) String logout) {
        LOGGER.debug("admin login page");
        ModelAndView view = (ModelAndView) model;
        view.addObject("adminLogin", adminLogin);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = null;
        try {
            userDetails = userDetailsService.loadUserByUsername(adminLogin.getSsoId());
        } catch (UsernameNotFoundException ex) {
            view.addObject("error", "Username not found !");
        }

        if (userDetails != null && userDetailsService.hasRole(userDetails, Role.ADMIN)) {
            view.setViewName("/admin/index");
            LOGGER.debug("returning admin index page");
        } else {
            LOGGER.debug("user is not admin");
            view.addObject("error", messageSource.getMessage("login.admin.invalidcredentials", null, request.getLocale()));
        }

        if (logout != null) {
            view.addObject("msg", "You've been logged out successfully.");
        }

        return view;

    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logoutPage(HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        return "redirect:/login?logout";
    }
}

@Component("adminLogin")
public class AdminLogin implements Serializable {

    private static final long serialVersionUID = -6394045014528037520L;

    private String ssoId;

    private String password;

    public AdminLogin() {
    }

    public AdminLogin(String ssoId, String password) {
        this.ssoId = ssoId;
        this.password = password;
    }

    public String getSsoId() {
        return ssoId;
    }

    public void setSsoId(String ssoId) {
        this.ssoId = ssoId;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

It's a strange behaviour..

The username parameter 'ssoId' is null as consequence. Thus the login fails with the configured error message.


Solution

  • My bad. I must be so tired when I posted this message.

    The issue was that my models were not mapped meaning that hibernate config file is not in classpath. Another problem is that username variable in security configuration was not the right one.

    thanks a lot.