@RequestMapping(value = "/authenticate", method = RequestMethod.POST) public ModelAndView authenticate( @RequestParam("username") String username, @RequestParam("password") String password) { UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password); ModelAndView modelAndView = new ModelAndView(); User user = userService.getUserByLogin(username); if (user != null) { if (!user.isEnabled()) { modelAndView.addObject("title", "Activate failed"); modelAndView.addObject("message", "You must activate before log in"); modelAndView.setViewName("error"); return modelAndView; } String token = securityUserService.authWithToken(authenticationToken); modelAndView.addObject("token", token); modelAndView.addObject("users", userService.findAllUsers()); modelAndView.addObject("currentUser", userService.getUserByToken(token)); modelAndView.setViewName("/profile"); return modelAndView; } modelAndView.addObject("title", "Invalid credentials "); modelAndView.addObject("message", "Check your login and password!"); modelAndView.setViewName("error"); return modelAndView; }
@RequestMapping(value = "/logout", method = RequestMethod.GET) public String logout(HttpServletRequest request) { securityUserService.logout(); Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals("AuthToken")) { cookie.setValue(null); } } return "index"; }
public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { if (!(servletRequest instanceof HttpServletRequest)) { throw new RuntimeException("Expected a http request"); } HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; String token = getToken(httpServletRequest); if (StringUtils.isNotEmpty(token)) { UsernamePasswordAuthenticationToken auth = securityUserService.getUserDetailsByToken(token); if (auth != null) { securityUserService.authenticate(auth); } } filterChain.doFilter(servletRequest, servletResponse); }