15.1.1 HttpServletRequest.getRemoteUser()獲得用戶名.java
HttpServletRequest.getUserPrincipal()獲得SecurityContextHolder.getContext().getAuthentication()的信息.web
Authentication auth = httpServletRequest.getUserPrincipal(); // assume integrated custom UserDetails called MyCustomUserDetails // by default, typically instance of UserDetails MyCustomUserDetails userDetails = (MyCustomUserDetails) auth.getPrincipal(); String firstName = userDetails.getFirstName(); String lastName = userDetails.getLastName();
是否有角色spring
boolean isAdmin = httpServletRequest.isUserInRole("ADMIN");
HttpServletRequest.authenticate(HttpServletRequest,HttpServletResponse) 能夠保證用戶被認證.若是用戶沒被認證,AuthenticaitonEntryPoint觸發認證.session
登錄app
try { httpServletRequest.login("user","password"); } catch(ServletException e) { // fail to authenticate }
登出異步
異步操做async
final AsyncContext async = httpServletRequest.startAsync(); async.start(new Runnable() { public void run() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); try { final HttpServletResponse asyncResponse = (HttpServletResponse) async.getResponse(); asyncResponse.setStatus(HttpServletResponse.SC_OK); asyncResponse.getWriter().write(String.valueOf(authentication)); async.complete(); } catch(Exception e) { throw new RuntimeException(e); } } });
異步輸出用戶信息url
servlet至少是3.0spa
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> </web-app>
下一步添加DelegatingFilterProxy的異步支持code
filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class> org.springframework.web.filter.DelegatingFilterProxy </filter-class> <async-supported>true</async-supported> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>ASYNC</dispatcher> </filter-mapping>
能夠用來對抗session固定攻擊.