实现会话功能
- 会话是指用户登入系统后,系统会记住该用户的登录状态,他可以在系统连续操作直到退出系统的过程。
- 认证的目的是对系统资源的保护,每次对资源的访问,系统必须得知道是谁在访问资源,才能对该请求进行合法性拦截。因此,在认证成功后,一般会把认证成功的用户信息放入Session中,在后续的请求中,系统能够从Session中获取到当当前用户,用这样的方式来实现会话机制。
- (1)增加会话控制
- 首先在UserDto中定义一个SESSION_USER_KEY,作为Session中存放登录用户信息的Key。
public static final String SESSION_USER_KEY = "_user";
- 然后修改LoginController,认证成功后,将用户信息放入当前会话。并增加用户登出方法,登出时将Session置为失效。
@RestController
public class LoginController {
@Autowired
AuthenticationService authenticationService;
@RequestMapping(value = "login", produces = "text/plain;charset=utf-8")
public String login(AuthenticationRequest authenticationRequest, HttpSession session) {
UserDto userDto = authenticationService.authentication(authenticationRequest);
//存入session
session.setAttribute(UserDto.SESSION_USER_KEY, userDto);
return userDto.getUsername() + "登录成功";
}
@RequestMapping(value = "/r/r1", produces = "text/plain;charset=utf-8")
public String r1(HttpSession session) {
String fullname = null;
Object object = session.getAttribute(UserDto.SESSION_USER_KEY);
if (object == null) {
fullname = "匿名";
} else {
UserDto userDto = (UserDto) object;
fullname = userDto.getFullname();
}
return fullname + "访问资源r1";
}
@GetMapping(value = "/logout", produces = "text/plain;charset=utf-8")
public String logout(HttpSession session) {
session.invalidate();
return "退出成功";
}
}