Я создал фильтр сервлета аутентификации, где я проверяю, присутствует ли заголовок сеанса или нет, а также проверяю его.Мой фильтр сервлетов будет выполнять эту строгую операцию, если у класса или метода ресурса есть аннотация аутентификации.
Вот мой AuthenticateFilter.java
@Slf4j
@Provider
@Authenticate
public class AuthenticateFilter implements Filter {
public static final String SESSION = "session";
public static final String USER_IP = "userIp";
private final SessionRepository sessionRepository;
@Context
private ResourceInfo resourceInfo;
@Inject
public AuthenticateFilter(
SessionRepository sessionRepository) {
this.sessionRepository = sessionRepository;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String sessionId = req.getHeader(HttpHeaders.AUTHORIZATION);
Optional<Session> optionalSession = Optional.empty();
if (sessionId != null) {
optionalSession = sessionRepository.getActiveSessionBySessionId(sessionId);
}
if (optionalSession.isPresent()) {
setContext(optionalSession.get());
chain.doFilter(request, response);
} else if (requiresAuthentication()) {
if(sessionId == null) {
throw new UnauthorizedException(UsersErrorCodes.UNAUTHORIZED_REQUEST,
"Session Id not present");
}
throw new UnauthorizedException(UsersErrorCodes.UNAUTHORIZED_REQUEST, "Session Expired");
}
chain.doFilter(request, response);
}
private Boolean requiresAuthentication() {
Class resourceClass = resourceInfo.getResourceClass();
Method resourceMethod = resourceInfo.getResourceMethod();
return resourceClass.isAnnotationPresent(Authenticate.class) || resourceMethod
.isAnnotationPresent(Authenticate.class);
}
private void setContext(Session session) {
return;
}
}
Здесь resourceInfo становится нулевым.
Вот так я регистрирую свой фильтр.
environment.servlets()
.addFilter("Authentication filter",
guiceBundle.getInjector().getProvider(AuthenticateFilter.class).get())
.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");