diff --git a/backend/src/main/java/io/metersphere/security/ApiKeyFilter.java b/backend/src/main/java/io/metersphere/security/ApiKeyFilter.java index 8634c18ae3..4a8b7d0dcc 100644 --- a/backend/src/main/java/io/metersphere/security/ApiKeyFilter.java +++ b/backend/src/main/java/io/metersphere/security/ApiKeyFilter.java @@ -15,36 +15,28 @@ public class ApiKeyFilter extends AnonymousFilter { @Override protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) { - try { - if (!SecurityUtils.getSubject().isAuthenticated()) { - String userId = ApiKeyHandler.getUser(WebUtils.toHttp(request)); - if (StringUtils.isNotBlank(userId)) { - if (LogUtil.getLogger().isDebugEnabled()) { - LogUtil.getLogger().debug("user auth: " + userId); - } - SecurityUtils.getSubject().login(new MsUserToken(userId, ApiKeySessionHandler.random, "LOCAL")); - } - } else { - if (ApiKeyHandler.isApiKeyCall(WebUtils.toHttp(request))) { - String userId = ApiKeyHandler.getUser(WebUtils.toHttp(request)); - SecurityUtils.getSubject().login(new MsUserToken(userId, ApiKeySessionHandler.random, "LOCAL")); - } else { - String id = (String) SecurityUtils.getSubject().getSession().getId(); - // 防止调用时使用 ak 作为 cookie 跳过登入逻辑 - if (id.length() < 20) { - SecurityUtils.getSubject().logout(); - } + // 不是apikey的通过 + if (!ApiKeyHandler.isApiKeyCall(WebUtils.toHttp(request))) { + String id = (String) SecurityUtils.getSubject().getSession().getId(); + // 防止调用时使用 ak 作为 cookie 跳过登入逻辑 + if (id.length() < 20) { + SecurityUtils.getSubject().logout(); + } + return true; + } + // apikey 验证 + if (!SecurityUtils.getSubject().isAuthenticated()) { + String userId = ApiKeyHandler.getUser(WebUtils.toHttp(request)); + if (StringUtils.isNotBlank(userId)) { + if (LogUtil.getLogger().isDebugEnabled()) { + LogUtil.getLogger().debug("user auth: " + userId); } + SecurityUtils.getSubject().login(new MsUserToken(userId, ApiKeySessionHandler.random, "LOCAL")); } - - if (!SecurityUtils.getSubject().isAuthenticated()) { - ((HttpServletResponse) response).setHeader(SessionConstants.AUTHENTICATION_STATUS, SessionConstants.AUTHENTICATION_INVALID); - } - } catch (Exception e) { - if (ApiKeyHandler.isApiKeyCall(WebUtils.toHttp(request))) { - throw e; - } - LogUtil.getLogger().error("failed to handle single sign on..", e); + } + // 登录之后验证 + if (!SecurityUtils.getSubject().isAuthenticated()) { + ((HttpServletResponse) response).setHeader(SessionConstants.AUTHENTICATION_STATUS, SessionConstants.AUTHENTICATION_INVALID); } return true;