1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.shiro.samples.sprhib.web;
20
21 import org.apache.shiro.SecurityUtils;
22 import org.apache.shiro.authc.AuthenticationException;
23 import org.apache.shiro.authc.UsernamePasswordToken;
24 import org.springframework.stereotype.Controller;
25 import org.springframework.ui.Model;
26 import org.springframework.validation.BindingResult;
27 import org.springframework.web.bind.annotation.ModelAttribute;
28 import org.springframework.web.bind.annotation.RequestMapping;
29 import org.springframework.web.bind.annotation.RequestMethod;
30
31
32
33
34 @Controller
35 public class SecurityController {
36
37 private LoginValidator loginValidator = new LoginValidator();
38
39 @RequestMapping(value="/login",method= RequestMethod.GET)
40 public String showLoginForm(Model model, @ModelAttribute LoginCommand command ) {
41 return "login";
42 }
43
44 @RequestMapping(value="/login",method= RequestMethod.POST)
45 public String login(Model model, @ModelAttribute LoginCommand command, BindingResult errors) {
46 loginValidator.validate(command, errors);
47
48 if( errors.hasErrors() ) {
49 return showLoginForm(model, command);
50 }
51
52 UsernamePasswordToken token = new UsernamePasswordToken(command.getUsername(), command.getPassword(), command.isRememberMe());
53 try {
54 SecurityUtils.getSubject().login(token);
55 } catch (AuthenticationException e) {
56 errors.reject( "error.login.generic", "Invalid username or password. Please try again." );
57 }
58
59 if( errors.hasErrors() ) {
60 return showLoginForm(model, command);
61 } else {
62 return "redirect:/s/home";
63 }
64 }
65
66 @RequestMapping("/logout")
67 public String logout() {
68 SecurityUtils.getSubject().logout();
69 return "redirect:/";
70 }
71
72
73 }