Skip to content

Commit

Permalink
SecurityUtils 加入获取当前登录用户ID方法,Security 结构调整
Browse files Browse the repository at this point in the history
  • Loading branch information
elunez committed Mar 10, 2020
1 parent 4054ac7 commit 207e6fb
Show file tree
Hide file tree
Showing 25 changed files with 159 additions and 145 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class ElPermissionConfig {

public Boolean check(String ...permissions){
// 获取当前用户的所有权限
List<String> elPermissions = SecurityUtils.getUserDetails().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
List<String> elPermissions = SecurityUtils.getCurrentUser().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
// 判断当前用户的所有权限是否包含接口上定义的权限
return elPermissions.contains("admin") || Arrays.stream(permissions).anyMatch(elPermissions::contains);
}
Expand Down
46 changes: 36 additions & 10 deletions eladmin-common/src/main/java/me/zhengjie/utils/SecurityUtils.java
Original file line number Diff line number Diff line change
@@ -1,34 +1,60 @@
package me.zhengjie.utils;

import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.exception.BadRequestException;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
* 获取当前登录的用户
* @author Zheng Jie
* @date 2019-01-17
*/
@Slf4j
public class SecurityUtils {

public static UserDetails getUserDetails() {
UserDetails userDetails;
try {
userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
} catch (Exception e) {
throw new BadRequestException(HttpStatus.UNAUTHORIZED, "登录状态过期");
/**
* 获取当前登录的用户
* @return UserDetails
*/
public static UserDetails getCurrentUser() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new BadRequestException(HttpStatus.UNAUTHORIZED, "当前登录状态过期");
}
return userDetails;
if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
UserDetailsService userDetailsService = SpringContextHolder.getBean(UserDetailsService.class);
return userDetailsService.loadUserByUsername(userDetails.getUsername());
}
throw new BadRequestException(HttpStatus.UNAUTHORIZED, "找不到当前登录的信息");
}

/**
* 获取系统用户名称
*
* @return 系统用户名称
*/
public static String getUsername(){
Object obj = getUserDetails();
return new JSONObject(obj).get("username", String.class);
public static String getCurrentUsername() {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new BadRequestException(HttpStatus.UNAUTHORIZED, "当前登录状态过期");
}
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
return userDetails.getUsername();
}

/**
* 获取系统用户ID
*
* @return 系统用户ID
*/
public static Long getCurrentUserId() {
UserDetails userDetails = getCurrentUser();
return new JSONObject(new JSONObject(userDetails).get("user")).get("id", Long.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {

public String getUsername() {
try {
return SecurityUtils.getUsername();
return SecurityUtils.getCurrentUsername();
}catch (Exception e){
return "";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public ResponseEntity<Object> getLogs(LogQueryCriteria criteria, Pageable pageab
@ApiOperation("用户日志查询")
public ResponseEntity<Object> getUserLogs(LogQueryCriteria criteria, Pageable pageable){
criteria.setLogType("INFO");
criteria.setBlurry(SecurityUtils.getUsername());
criteria.setBlurry(SecurityUtils.getCurrentUsername());
return new ResponseEntity<>(logService.queryAllByUser(criteria,pageable), HttpStatus.OK);
}

Expand Down
2 changes: 1 addition & 1 deletion eladmin-system/src/main/java/me/zhengjie/AppRun.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@
import org.springframework.web.bind.annotation.RestController;

/**
* 开启审计功能 -> @EnableJpaAuditing
* @author Zheng Jie
* @date 2018/11/15 9:20:19
*/
@EnableAsync
@RestController
/** 开启审计功能 */
@EnableJpaAuditing(auditorAwareRef = "auditorAware")
@SpringBootApplication
@EnableTransactionManagement
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

/**
* @描述 : 设置审计
* @作者 : Dong ZhaoYang
* @author : Dong ZhaoYang
* @日期 : 2019/10/28
* @时间 : 10:29
*/
Expand All @@ -18,11 +18,11 @@ public class AuditorConfig implements AuditorAware<String> {
/**
* 返回操作员标志信息
*
* @return
* @return /
*/
@Override
public Optional<String> getCurrentAuditor() {
// 这里应根据实际业务情况获取具体信息
return Optional.of(SecurityUtils.getUsername());
return Optional.of(SecurityUtils.getCurrentUsername());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public DataScope(UserService userService, RoleService roleService, DeptService d

public Set<Long> getDeptIds() {

UserDto user = userService.findByName(SecurityUtils.getUsername());
UserDto user = userService.findByName(SecurityUtils.getCurrentUsername());

// 用于存储部门id
Set<Long> deptIds = new HashSet<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ private void backupApp(ExecuteShellUtil executeShellUtil, String ip, String file
//还原信息入库
DeployHistory deployHistory = new DeployHistory();
deployHistory.setAppName(appName);
deployHistory.setDeployUser(SecurityUtils.getUsername());
deployHistory.setDeployUser(SecurityUtils.getCurrentUsername());
deployHistory.setIp(ip);
deployHistory.setDeployId(id);
deployHistoryService.create(deployHistory);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final JwtAccessDeniedHandler jwtAccessDeniedHandler;
private final ApplicationContext applicationContext;


public SecurityConfig(TokenProvider tokenProvider, CorsFilter corsFilter, JwtAuthenticationEntryPoint authenticationErrorHandler, JwtAccessDeniedHandler jwtAccessDeniedHandler, ApplicationContext applicationContext) {
this.tokenProvider = tokenProvider;
this.corsFilter = corsFilter;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.security.config.SecurityProperties;
import me.zhengjie.modules.security.security.TokenProvider;
import me.zhengjie.modules.security.security.vo.AuthUser;
import me.zhengjie.modules.security.security.vo.JwtUser;
import me.zhengjie.modules.security.service.dto.AuthUserDto;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.security.service.OnlineUserService;
import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.SecurityUtils;
Expand Down Expand Up @@ -42,7 +42,7 @@
@RestController
@RequestMapping("/auth")
@Api(tags = "系统:系统授权接口")
public class AuthController {
public class AuthorizationController {

@Value("${loginCode.expiration}")
private Long expiration;
Expand All @@ -57,7 +57,7 @@ public class AuthController {
private final TokenProvider tokenProvider;
private final AuthenticationManagerBuilder authenticationManagerBuilder;

public AuthController(SecurityProperties properties, RedisUtils redisUtils, UserDetailsService userDetailsService, OnlineUserService onlineUserService, TokenProvider tokenProvider, AuthenticationManagerBuilder authenticationManagerBuilder) {
public AuthorizationController(SecurityProperties properties, RedisUtils redisUtils, UserDetailsService userDetailsService, OnlineUserService onlineUserService, TokenProvider tokenProvider, AuthenticationManagerBuilder authenticationManagerBuilder) {
this.properties = properties;
this.redisUtils = redisUtils;
this.userDetailsService = userDetailsService;
Expand All @@ -70,7 +70,7 @@ public AuthController(SecurityProperties properties, RedisUtils redisUtils, User
@ApiOperation("登录授权")
@AnonymousAccess
@PostMapping(value = "/login")
public ResponseEntity<Object> login(@Validated @RequestBody AuthUser authUser, HttpServletRequest request){
public ResponseEntity<Object> login(@Validated @RequestBody AuthUserDto authUser, HttpServletRequest request){
// 密码解密
RSA rsa = new RSA(privateKey, null);
String password = new String(rsa.decrypt(authUser.getPassword(), KeyType.PrivateKey));
Expand All @@ -91,13 +91,13 @@ public ResponseEntity<Object> login(@Validated @RequestBody AuthUser authUser, H
SecurityContextHolder.getContext().setAuthentication(authentication);
// 生成令牌
String token = tokenProvider.createToken(authentication);
final JwtUser jwtUser = (JwtUser) authentication.getPrincipal();
final JwtUserDto jwtUserDto = (JwtUserDto) authentication.getPrincipal();
// 保存在线信息
onlineUserService.save(jwtUser, token, request);
onlineUserService.save(jwtUserDto, token, request);
// 返回 token 与 用户信息
Map<String,Object> authInfo = new HashMap<String,Object>(2){{
put("token", properties.getTokenStartWith() + token);
put("user", jwtUser);
put("user", jwtUserDto);
}};
if(singleLogin){
//踢掉之前已经登录的token
Expand All @@ -109,8 +109,8 @@ public ResponseEntity<Object> login(@Validated @RequestBody AuthUser authUser, H
@ApiOperation("获取用户信息")
@GetMapping(value = "/info")
public ResponseEntity<Object> getUserInfo(){
JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(SecurityUtils.getUsername());
return ResponseEntity.ok(jwtUser);
JwtUserDto jwtUserDto = (JwtUserDto)userDetailsService.loadUserByUsername(SecurityUtils.getCurrentUsername());
return ResponseEntity.ok(jwtUserDto);
}

@AnonymousAccess
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.security.config.SecurityProperties;
import me.zhengjie.modules.security.security.vo.OnlineUser;
import me.zhengjie.modules.security.service.dto.OnlineUserDto;
import me.zhengjie.modules.security.service.OnlineUserService;
import me.zhengjie.utils.SpringContextHolder;
import org.springframework.security.core.Authentication;
Expand Down Expand Up @@ -36,15 +36,15 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo
String token = resolveToken(httpServletRequest);
String requestRri = httpServletRequest.getRequestURI();
// 验证 token 是否存在
OnlineUser onlineUser = null;
OnlineUserDto onlineUserDto = null;
try {
SecurityProperties properties = SpringContextHolder.getBean(SecurityProperties.class);
OnlineUserService onlineUserService = SpringContextHolder.getBean(OnlineUserService.class);
onlineUser = onlineUserService.getOne(properties.getOnlineKey() + token);
onlineUserDto = onlineUserService.getOne(properties.getOnlineKey() + token);
} catch (ExpiredJwtException e) {
log.error(e.getMessage());
}
if (onlineUser != null && StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
if (onlineUserDto != null && StringUtils.hasText(token) && tokenProvider.validateToken(token)) {
Authentication authentication = tokenProvider.getAuthentication(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
log.debug("set Authentication to security context for '{}', uri: {}", authentication.getName(), requestRri);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.security.config.SecurityProperties;
import me.zhengjie.modules.security.security.vo.JwtUser;
import me.zhengjie.modules.security.security.vo.OnlineUser;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.security.service.dto.OnlineUserDto;
import me.zhengjie.utils.*;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
Expand All @@ -30,22 +30,22 @@ public OnlineUserService(SecurityProperties properties, RedisUtils redisUtils) {

/**
* 保存在线用户信息
* @param jwtUser /
* @param jwtUserDto /
* @param token /
* @param request /
*/
public void save(JwtUser jwtUser, String token, HttpServletRequest request){
String job = jwtUser.getDept() + "/" + jwtUser.getJob();
public void save(JwtUserDto jwtUserDto, String token, HttpServletRequest request){
String job = jwtUserDto.getUser().getDept().getName() + "/" + jwtUserDto.getUser().getJob().getName();
String ip = StringUtils.getIp(request);
String browser = StringUtils.getBrowser(request);
String address = StringUtils.getCityInfo(ip);
OnlineUser onlineUser = null;
OnlineUserDto onlineUserDto = null;
try {
onlineUser = new OnlineUser(jwtUser.getUsername(), jwtUser.getNickName(), job, browser , ip, address, EncryptUtils.desEncrypt(token), new Date());
onlineUserDto = new OnlineUserDto(jwtUserDto.getUsername(), jwtUserDto.getUser().getNickName(), job, browser , ip, address, EncryptUtils.desEncrypt(token), new Date());
} catch (Exception e) {
e.printStackTrace();
}
redisUtils.set(properties.getOnlineKey() + token, onlineUser, properties.getTokenValidityInSeconds()/1000);
redisUtils.set(properties.getOnlineKey() + token, onlineUserDto, properties.getTokenValidityInSeconds()/1000);
}

/**
Expand All @@ -55,10 +55,10 @@ public void save(JwtUser jwtUser, String token, HttpServletRequest request){
* @return /
*/
public Map<String,Object> getAll(String filter, Pageable pageable){
List<OnlineUser> onlineUsers = getAll(filter);
List<OnlineUserDto> onlineUserDtos = getAll(filter);
return PageUtil.toPage(
PageUtil.toPage(pageable.getPageNumber(),pageable.getPageSize(),onlineUsers),
onlineUsers.size()
PageUtil.toPage(pageable.getPageNumber(),pageable.getPageSize(), onlineUserDtos),
onlineUserDtos.size()
);
}

Expand All @@ -67,28 +67,27 @@ public Map<String,Object> getAll(String filter, Pageable pageable){
* @param filter /
* @return /
*/
public List<OnlineUser> getAll(String filter){
public List<OnlineUserDto> getAll(String filter){
List<String> keys = redisUtils.scan(properties.getOnlineKey() + "*");
Collections.reverse(keys);
List<OnlineUser> onlineUsers = new ArrayList<>();
List<OnlineUserDto> onlineUserDtos = new ArrayList<>();
for (String key : keys) {
OnlineUser onlineUser = (OnlineUser) redisUtils.get(key);
OnlineUserDto onlineUserDto = (OnlineUserDto) redisUtils.get(key);
if(StringUtils.isNotBlank(filter)){
if(onlineUser.toString().contains(filter)){
onlineUsers.add(onlineUser);
if(onlineUserDto.toString().contains(filter)){
onlineUserDtos.add(onlineUserDto);
}
} else {
onlineUsers.add(onlineUser);
onlineUserDtos.add(onlineUserDto);
}
}
onlineUsers.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime()));
return onlineUsers;
onlineUserDtos.sort((o1, o2) -> o2.getLoginTime().compareTo(o1.getLoginTime()));
return onlineUserDtos;
}

/**
* 踢出用户
* @param key /
* @throws Exception /
*/
public void kickOut(String key){
key = properties.getOnlineKey() + key;
Expand All @@ -110,9 +109,9 @@ public void logout(String token) {
* @param response /
* @throws IOException /
*/
public void download(List<OnlineUser> all, HttpServletResponse response) throws IOException {
public void download(List<OnlineUserDto> all, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (OnlineUser user : all) {
for (OnlineUserDto user : all) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("用户名", user.getUserName());
map.put("岗位", user.getJob());
Expand All @@ -130,23 +129,23 @@ public void download(List<OnlineUser> all, HttpServletResponse response) throws
* @param key /
* @return /
*/
public OnlineUser getOne(String key) {
return (OnlineUser)redisUtils.get(key);
public OnlineUserDto getOne(String key) {
return (OnlineUserDto)redisUtils.get(key);
}

/**
* 检测用户是否在之前已经登录,已经登录踢下线
* @param userName 用户名
*/
public void checkLoginOnUser(String userName, String igoreToken){
List<OnlineUser> onlineUsers = getAll(userName);
if(onlineUsers ==null || onlineUsers.isEmpty()){
List<OnlineUserDto> onlineUserDtos = getAll(userName);
if(onlineUserDtos ==null || onlineUserDtos.isEmpty()){
return;
}
for(OnlineUser onlineUser:onlineUsers){
if(onlineUser.getUserName().equals(userName)){
for(OnlineUserDto onlineUserDto : onlineUserDtos){
if(onlineUserDto.getUserName().equals(userName)){
try {
String token =EncryptUtils.desDecrypt(onlineUser.getKey());
String token =EncryptUtils.desDecrypt(onlineUserDto.getKey());
if(StringUtils.isNotBlank(igoreToken)&&!igoreToken.equals(token)){
this.kickOut(token);
}else if(StringUtils.isBlank(igoreToken)){
Expand Down
Loading

0 comments on commit 207e6fb

Please sign in to comment.