Skip to content
Permalink
Browse files
prevent NullPointerException on AuthInterceptor/ make session timeout…
… configurable (#691)

Co-authored-by: PENG TANG <pengtang@PENGs-MacBook-Pro.local>
  • Loading branch information
chrisptang and PENG TANG committed Feb 3, 2021
1 parent 94688a0 commit 44741e250094fb380642989e8f12a00bc2384b63
Showing 1 changed file with 27 additions and 3 deletions.
@@ -22,17 +22,25 @@
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.lang.reflect.Method;

@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
@Value("${admin.check.authority:true}")
private boolean checkAuthority;

//make session timeout configurable
//default to be an hour:1000 * 60 * 60
@Value("${admin.check.sessionTimeoutMilli:3600000}")
private long sessionTimeoutMilli;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod) || !checkAuthority) {
@@ -44,17 +52,33 @@ public boolean preHandle(HttpServletRequest request, HttpServletResponse respons
if (null == authority) {
authority = method.getDeclaringClass().getDeclaredAnnotation(Authority.class);
}

String authorization = request.getHeader("Authorization");
if (null != authority && authority.needLogin()) {
String authorization = request.getHeader("Authorization");
//check if 'authorization' is empty to prevent NullPointException
//since UserController.tokenMap is an instance of ConcurrentHashMap.
if (StringUtils.isEmpty(authorization)) {
//While authentication is required and 'Authorization' string is missing in the request headers,
//reject this request(http403).
rejectedResponse(response);
return false;
}

UserController.User user = UserController.tokenMap.get(authorization);
if (null != user && System.currentTimeMillis() - user.getLastUpdateTime() <= 1000 * 60 * 60) {
if (null != user && System.currentTimeMillis() - user.getLastUpdateTime() <= sessionTimeoutMilli) {
user.setLastUpdateTime(System.currentTimeMillis());
return true;
}
response.setStatus(HttpStatus.UNAUTHORIZED.value());

//while user not found, or session timeout, reject this request(http403).
rejectedResponse(response);
return false;
} else {
return true;
}
}

private static void rejectedResponse(@NotNull HttpServletResponse response) {
response.setStatus(HttpStatus.UNAUTHORIZED.value());
}
}

0 comments on commit 44741e2

Please sign in to comment.