我正在使用spring security v3.1.4.我想要实现的是让管理员能够注销常规用户(使他的会话无效).用户只能在任何给定时间登录一次,但如果他忘记退出,那么当他尝试从其他位置登录时,他将无法登录.所以他会把一张票给管理员和管理员将使他之前登录的所有会话无效(希望只有一个).
在我的web.xml中,我有以下定义.
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
Run Code Online (Sandbox Code Playgroud)
在我的春天安全xml我有以下定义.
<session-management invalid-session-url="/home">
<concurrency-control max-sessions="1" error-if-maximum-exceeded="true" session-registry-ref="sessionRegistry"/>
</session-management>
<beans:bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl"/>
Run Code Online (Sandbox Code Playgroud)
然后我有一个类似休息的控制器来执行注销.
@Controller
@RequestMapping("/api/admin")
public class RestAdminController {
static final Set<SimpleGrantedAuthority> AUTHS = new HashSet<>();
static {
AUTHS.add(new SimpleGrantedAuthority("ROLE_USER"));
}
@Autowired
private SessionRegistry sessionRegistry;
@RequestMapping("/user/logout");
public @ResponseBody String logout(@RequestBody Account account) {
User user = new User(account.getUsername(), "", AUTHS);
List<SessionInformation> infos = sessionRegistry.getAllSessions(u, false);
for(SessionInformation info : infos) {
info.expireNow(); //expire the session
sessionRegistry.removeSessionInformation(info.getSessionId()); //remove session
}
return "ok";
}
}
Run Code Online (Sandbox Code Playgroud)
当我从同一台计算机上测试时,这段代码"kinda"有效.假设我们有一个用户USER_A和一个管理员ADMIN_A.