TokenExtractor { public static String extract(Request request) { List<String> authorizationHeaders = request.headers() != null ? request.headers().get(HttpHeaders.AUTHORIZATION) : null; if (authorizationHeaders != null && !authorizationHeaders.isEmpty()) { Optional<String> authorizationBearerHeader = authorizationHeaders .stream() .filter(h -> StringUtils.startsWithIgnoreCase(h, BEARER)) .findFirst(); if (authorizationBearerHeader.isPresent()) { String authToken = authorizationBearerHeader.get().substring(BEARER.length()).trim(); if (!authToken.isEmpty()) { return authToken; } } } return request.parameters() != null ? request.parameters().getFirst(ACCESS_TOKEN) : null; }  static String extract(Request request);  }
@Test public void shouldNotExtract_noAuthorizationHeader() { HttpHeaders headers = new HttpHeaders(); when(request.headers()).thenReturn(headers); when(request.parameters()).thenReturn(new LinkedMultiValueMap<>()); String token = TokenExtractor.extract(request); Assert.assertNull(token); }
@Test public void shouldNotExtract_unknownAuthorizationHeader() { String jwt = "dummy-token"; HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Basic " + jwt); when(request.headers()).thenReturn(headers); String token = TokenExtractor.extract(request); Assert.assertNull(token); }
@Test public void shouldNotExtract_bearerAuthorizationHeader_noValue() { String jwt = "dummy-token"; HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", TokenExtractor.BEARER); when(request.headers()).thenReturn(headers); String token = TokenExtractor.extract(request); Assert.assertNull(token); }
@Test public void shouldExtract_fromHeader() { String jwt = "dummy-token"; HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", TokenExtractor.BEARER + ' ' + jwt); when(request.headers()).thenReturn(headers); String token = TokenExtractor.extract(request); Assert.assertNotNull(token); Assert.assertEquals(jwt, token); }
@Test public void shouldExtract_fromQueryParameter() { String jwt = "dummy-token"; HttpHeaders headers = new HttpHeaders(); when(request.headers()).thenReturn(headers); LinkedMultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.add(TokenExtractor.ACCESS_TOKEN, jwt); when(request.parameters()).thenReturn(parameters); String token = TokenExtractor.extract(request); Assert.assertNotNull(token); Assert.assertEquals(jwt, token); }