Добрый день.
Делаю приложение для jwt аутентификации на примере кода из курсов.
Все работает, но непонятны некоторые механизмы, используемые в коде.
Есть кастомный http фильтр для получения jwt токенов.
Он добавлен перед ExceptionTranslationFilter.
Все запросы требуют аутентифицированного пользователя.
Пользователь отправляет запрос POST на /jwt/tokens:
localhost:8080/jwt/tokens
Authorization: Basic bas64(логин:пароль)
HttpBasicFilter отрабатывает запрос и сохраняет данные пользователя в SecurityContexHolder.
Далее идут следующие фильтры, в т.ч. мой RequestJwtTokensFilter.
Вот часть его кода:
public class RequestJwtTokensFilter extends OncePerRequestFilter {
private RequestMatcher requestMatcher = new AntPathRequestMatcher("/jwt/tokens", HttpMethod.POST.name());
private SecurityContextRepository securityContextRepository = new RequestAttributeSecurityContextRepository();
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
if (this.requestMatcher.matches(request)) {
if (this.securityContextRepository.containsContext(request)) {
var context = this.securityContextRepository.loadDeferredContext(request).get();
if (context != null && !(context.getAuthentication() instanceof PreAuthenticatedAuthenticationToken)) {
return;
}
}
throw new AccessDeniedException("User must be authenticated");
}
filterChain.doFilter(request, response);
}
}
Собственно, мне непонятно, что происходит здесь:
if (this.securityContextRepository.containsContext(request))
Мы создаем RequestAttributeSecurityContextRepository, очевидно он имеет доступ к SecurityContexHolder и SecurityContex.
А вот что происходит дальше?
Судя по тому что я нарыл, где-то до RequestJwtTokensFilter кто-то должен сохранить SecurityContex как атрибут HttpServletRequest - request.setAttribute()
А RequestAttributeSecurityContextRepository должен проверить что SecurityContex из HttpServletRequest есть в SecurityContexHolder?
Вобщем, не очень понятно что тут происходит.