前言
接上文 《Spring Boot 注册登录demo 使用Spring Security和发送短信验证码》
我在我的Web应用程序中使用spring security,现在我想要列出所有登录我程序的用户.
我怎样才能访问该列表?它们不是已经存在于spring框架内的某个地方吗?像SecurityContextHolder或SecurityContextRepository? 下面就说我怎么搞的。
1、注入SessionRegistry
@Bean
public SessionRegistry sessionRegistry() {
return new SessionRegistryImpl();
}
2、配置类configure 方法中增加如下配置
http.sessionManagement()
.maximumSessions(1)
.maxSessionsPreventsLogin(true)
.sessionRegistry(sessionRegistry());
上面这两个在同一个配置类里面,完整的配置类 可以看后面源码 。
3、获取所有的登录用户
import com.king.security.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class LoginUserServiceImpl {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
SessionRegistry sessionRegistry;
public List<User> getLoginUser() {
List<Object> list = sessionRegistry.getAllPrincipals();
logger.info("在线人数=[{}]", list.size());
List<User> userList = new ArrayList<>();
for (Object o : list) {
if (o instanceof User) {
User user = (User) o;
userList.add(user);
}
}
return userList;
}
}
4、写个接口测试一下
import com.king.security.service.LoginUserServiceImpl;
import com.king.security.vo.ResultObj;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/loginUser")
@Api(value = "获取全部登录用户", tags = "获取全部登录用户")
public class LoginUserController {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private LoginUserServiceImpl loginUserService;
@ApiOperation("获取全部登录用户")
@GetMapping("/getAllLoginUser.do")
public ResultObj getAllLoginUser() {
return ResultObj.ok(loginUserService.getLoginUser());
}
}
5、测试结果
6、源码地址
Github https://github.com/KingJin-web/springboot
Gitee https://gitee.com/KingJin-web/springboot
|