日志组件使用观察者模式,spring security 无法获取登录用户信息

avatar 2022年11月04日17:04:27 0 1750 views
博主分享免费Java教学视频,B站账号:Java刘哥 ,长期提供技术问题解决、项目定制:本站商品点此

使用spring观察者模式将操作日志写入到数据库中

如下代码,主要是第四段代码 LogUtil 里 SecurityUtil.getCurrentUser() 一直为空

直接说解决办法吧

解决办法

设置安全策略为 MODE_INHERITABLETHREADLOCAL

在启动类里加 

SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);

 public static void main(String[] args) {
       // 解决服务日志模块获取不到当前用户信息问题
       SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
       SpringApplication.run(ThemeApplication.class, args);
 }

或者

配置属性

spring.security.strategy=MODE_INHERITABLETHREADLOCAL

 

完整代码如下

1、LogPublisher

public class LogPublisher {
    public LogPublisher() {
    }

    public static void publishEvent(String methodClass, String methodName, Loggable loggable, long begin, long end) {
        HttpServletRequest request = WebUtil.getRequest();
        Date beginTime = Calendar.getInstance().getTime();
        beginTime.setTime(begin);
        Date endTime = Calendar.getInstance().getTime();
        beginTime.setTime(end);
        Log log = new Log();
        log.setTitle(loggable.value());
        log.setType(loggable.type());
        log.setStartTime(beginTime);
        log.setEndTime(endTime);
        log.setCost(end - begin);
        log.setMethodClass(methodClass);
        log.setMethodName(methodName);
        LogUtil.setLogRequest(request, log);
        Map<String, Object> event = new HashMap(16);
        event.put("log", log);
        if (DataContext.currentContext() != null && DataContext.currentContext().containsKey("CTX_SPACE_ID")) {
            event.put("CTX_SPACE_ID", DataContext.currentContext("CTX_SPACE_ID"));
        }

        SpringContext.publishEvent(new LogEvent(event));
    }
}

2、LogEvent

public class LogEvent extends ApplicationEvent {
    public LogEvent(Map<String, Object> source) {
        super(source);
    }
}

3、LogListener

public class LogListener {
    private static final Logger log = LoggerFactory.getLogger(LogListener.class);
    private @NonNull LogClient logClient;
    private @NonNull SystemProperties systemProperties;
    private @NonNull AppInfo appInfo;
    @Value("${spring.application.name}")
    private String applicationName;

    @Async
    @Order
    @EventListener({LogEvent.class})
    public void saveLog(LogEvent event) {
        Map<String, Object> source = (Map)event.getSource();
        Log log = (Log)source.get("log");
        if (source.containsKey("CTX_SPACE_ID")) {
            log.setSpaceId((String)source.get("CTX_SPACE_ID"));
        }

        log.setServiceId(this.applicationName);
        LogUtil.additionalLogRequest(log, this.systemProperties, this.appInfo);
        this.logClient.saveLog(log);
    }

    public LogListener(final @NonNull LogClient logClient, final @NonNull SystemProperties systemProperties, final @NonNull AppInfo appInfo) {
        if (logClient == null) {
            throw new NullPointerException("logClient is marked non-null but is null");
        } else if (systemProperties == null) {
            throw new NullPointerException("systemProperties is marked non-null but is null");
        } else if (appInfo == null) {
            throw new NullPointerException("appInfo is marked non-null but is null");
        } else {
            this.logClient = logClient;
            this.systemProperties = systemProperties;
            this.appInfo = appInfo;
        }
    }
}

4、LogUtil

public final class LogUtil {
    public static void setLogRequest(HttpServletRequest request, LogBase logBase) {
        logBase.setRemoteIp(WebUtil.getIpAddr(request));
        logBase.setUserAgent(request.getHeader("user-agent"));
        logBase.setRequestUri(UriUtil.getUriPath(request.getRequestURI()));
        logBase.setRequestMethod(request.getMethod());
        logBase.setRequestParam(WebUtil.getRequestParam(request));
    }

    public static void additionalLogRequest(LogBase log, SystemProperties systemProperties, AppInfo appInfo) {
        log.setSystemId(systemProperties.getSystemCode());
        if (SecurityUtil.getCurrentUser() != null) {
            CoreUser coreUser = SecurityUtil.getCurrentCoreUser();
            log.setUserId(coreUser.getUserId());
            log.setUserName(coreUser.getUserName());
            log.setUnitId(coreUser.getUnitId());
            log.setUnitCode(coreUser.getUnitCode());
            log.setUnitName(coreUser.getUnitName());
        }

        log.setServerIp(appInfo.getIp());
        log.setServerHost(appInfo.getHostName());
        log.setEnv(SpringContext.getActiveProfile());
    }

    private LogUtil() {
        throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
    }
}

 

  • 微信
  • 交流学习,资料分享
  • weinxin
  • 个人淘宝
  • 店铺名:言曌博客咨询部

  • (部分商品未及时上架淘宝)
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0