refactor: 优化ApiKeyFilter的执行流程

This commit is contained in:
CaptainB 2022-06-26 09:26:46 +08:00 committed by f2c-ci-robot[bot]
parent c6d21be372
commit fc738a253d
1 changed files with 20 additions and 28 deletions

View File

@ -15,36 +15,28 @@ public class ApiKeyFilter extends AnonymousFilter {
@Override @Override
protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) { protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) {
try { // 不是apikey的通过
if (!SecurityUtils.getSubject().isAuthenticated()) { if (!ApiKeyHandler.isApiKeyCall(WebUtils.toHttp(request))) {
String userId = ApiKeyHandler.getUser(WebUtils.toHttp(request)); String id = (String) SecurityUtils.getSubject().getSession().getId();
if (StringUtils.isNotBlank(userId)) { // 防止调用时使用 ak 作为 cookie 跳过登入逻辑
if (LogUtil.getLogger().isDebugEnabled()) { if (id.length() < 20) {
LogUtil.getLogger().debug("user auth: " + userId); SecurityUtils.getSubject().logout();
} }
SecurityUtils.getSubject().login(new MsUserToken(userId, ApiKeySessionHandler.random, "LOCAL")); return true;
} }
} else { // apikey 验证
if (ApiKeyHandler.isApiKeyCall(WebUtils.toHttp(request))) { if (!SecurityUtils.getSubject().isAuthenticated()) {
String userId = ApiKeyHandler.getUser(WebUtils.toHttp(request)); String userId = ApiKeyHandler.getUser(WebUtils.toHttp(request));
SecurityUtils.getSubject().login(new MsUserToken(userId, ApiKeySessionHandler.random, "LOCAL")); if (StringUtils.isNotBlank(userId)) {
} else { if (LogUtil.getLogger().isDebugEnabled()) {
String id = (String) SecurityUtils.getSubject().getSession().getId(); LogUtil.getLogger().debug("user auth: " + userId);
// 防止调用时使用 ak 作为 cookie 跳过登入逻辑
if (id.length() < 20) {
SecurityUtils.getSubject().logout();
}
} }
SecurityUtils.getSubject().login(new MsUserToken(userId, ApiKeySessionHandler.random, "LOCAL"));
} }
}
if (!SecurityUtils.getSubject().isAuthenticated()) { // 登录之后验证
((HttpServletResponse) response).setHeader(SessionConstants.AUTHENTICATION_STATUS, SessionConstants.AUTHENTICATION_INVALID); 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);
} }
return true; return true;