HeaderRequestTokenExtractor implements RequestTokenExtractor { @Override public String getToken(HttpServletRequest req) { if (req.getHeader(HttpHeaders.AUTHORIZATION) == null) { return null; } if (req.getHeader(HttpHeaders.AUTHORIZATION).toLowerCase().startsWith("bearer")) { String[] parts = req.getHeader(HttpHeaders.AUTHORIZATION).split(" "); if (parts.length != 2) { throw new BadRequestException("Invalid authorization header format."); } return parts[1]; } else { return req.getHeader(HttpHeaders.AUTHORIZATION); } }  @Override String getToken(HttpServletRequest req);  }
@Test(dataProvider = "validHeadersProvider") public void shouldExtractTokensFromValidHeaders(String headerValue, String expectedToken) { when(servletRequest.getHeader(eq(AUTHORIZATION))).thenReturn(headerValue); String token = tokenExtractor.getToken(servletRequest); assertEquals(token, expectedToken); }
@Test( dataProvider = "invalidHeadersProvider", expectedExceptions = BadRequestException.class, expectedExceptionsMessageRegExp = "Invalid authorization header format.") public void shouldThrowExceptionOnInvalidToken(String headerValue) { when(servletRequest.getHeader(eq(AUTHORIZATION))).thenReturn(headerValue); tokenExtractor.getToken(servletRequest); }