# 第十二章 Spring Security 与 Servlet API 集成
一、与 Servlet 2.0 的集成
1. getRemoteUser()
HttpServletRequest.getRemoteUser() 返回 SecurityContextHolder.getContext().getAuthentication().getName()
2. getUserPrincipal()
HttpServletRequest.getUserPrincipal() 返回 SecurityContextHolder.getContext().getAuthentication(),返回结果类型为 Authentication,当使用用户名、密码的方式进行的身份验证时,其为 UsernamePasswordAuthenticationToken 的一个实例。
可以通过 Authentication.getPrincipal() 方法,将其转换为 UserDetails 的实现类.
3. isUserInRole(String)
HttpServletRequest.isUserInRole(String) 返回 SecurityContextHolder.getContext().getAuthentication().getAuthorities() 是否包含传入的 String,getAuthorities() 返回一个 GrantedAuthority 集合。
用户通常不需要传入 “ROLE” 前缀,它由系统自动添加。
二、与 Servlet 3.0 的集成
4. authenticate(HttpServletRequest,HttpServletResponse)
通过 HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse) 方法可以确保用户得到了身份验证。如果它们未经过身份验证,将会使用 AuthenticationEntryPoint 请求用户进行身份验证(如重定向至登录页)。
5. login(String,String)
HttpServletRequest.login(String,String) 可用于使用当前 AuthenticationManager 对用户进行身份验证。
try{
httpServletRequest.login("username","password");
} catch(ServletException e) {
// fail to authenticate,失败信息
}
如果需要 Spring Security 处理失败的身份验证,则不用捕获 ServletException。
6. logout()
使用 HttpServletRequest.logout() 将当前用户注销。
通常这意味着会将 SecurityContextHolder 清除、HttpSession 失效、任何与 “RememberMe”相关的身份验证将被清除,等等。但是如果你自定义了 LogoutHandler,则将根据具体配置来,注意你仍然需要定义服务端的相应(比如重定向至登录页等)。
7. 异步请求
三、与 Servlet 3.1 的集成
8. changeSessionId()
HttpServletRequest.changeSessionId() 是 Servlet3.1 及更高版本中,防止会话固定攻击的默认方法。