Spring Boot整合Spring Security简记-S
2018-01-17 本文已影响168人
78240024406c
new無语 转载请注明原创出处,谢谢!
本节介绍Spring Security如何与Servlet集成。
Servlet 2.5+集成
HttpServletRequest.getRemoteUser()
返回结果为SecurityContextHolder.getContext().getAuthentication().getName()
,一般为当前认证用户名。还可检验是否已验证或匿名。
HttpServletRequest.getUserPrincipal()
返回结果为SecurityContextHolder.getContext().getAuthentication()
的认证用户信息主体。
Authentication authentication = (Authentication) httpServletRequest.getUserPrincipal();
Object principal = authentication.getPrincipal();
Object userDetails = null;
if (principal instanceof UserDetails) {
userDetails = (UserDetails) principal;
} else {
userDetails = principal.toString();
}
Servlet 3+集成
HttpServletRequest.isUserInRole(String)
判断是否包含目标角色权限。是否在SecurityContextHolder.getContext().getAuthentication().getAuthorities()
中存在。不用将ROLE_
填入,因为在方法验证中,自动添加。
boolean isAdmin = httpServletRequest.isUserInRole("ADMIN");
Servlet 3.1+集成
HttpServletRequest.authenticate(HttpServletResponse)
判断当前请求是否认证用户。
HttpServletRequest.login(String,String)
使用username和password进行身份认证。
try {
httpServletRequest.login("user","password");
} catch(ServletException e) {
// fail to authenticate
}
注:如果需要Spring Security进行处理身份认证失败的异常,就不需要捕获ServletException 异常。
HttpServletRequest.logout()
可用于退出当前用户。
AsyncContext.start(Runnable)
Spring Srcurity覆盖AsyncContext.start(Runnable)
方法,以确保当前线程SecurityContext
传播到新线程。
final AsyncContext asyncContext = httpServletRequest.startAsync();
asyncContext.start(new Runnable() {
@Override
public void run() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
try {
final HttpServletResponse asyncResponse = (HttpServletResponse) asyncContext.getResponse();
asyncResponse.setStatus(HttpServletResponse.SC_OK);
asyncResponse.getWriter().write(String.valueOf(authentication));
asyncContext.complete();
} catch (Exception e) {
logger.error("", e);
}
}
});