refactor: 优化ApiKeyFilter的执行流程

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

View File

@ -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;