AntiCsrfHelper extends ComponentSupport { public void requireValidToken(final HttpServletRequest httpRequest, @Nullable final String token) { Optional<String> optToken = token == null ? Optional.ofNullable(httpRequest.getHeader(ANTI_CSRF_TOKEN_NAME)) : Optional.of(token); if (!enabled || isNotBrowserRequest(httpRequest) || isAntiCsrfTokenValid(httpRequest, optToken)) { return; } throw new UnauthorizedException(ERROR_MESSAGE_TOKEN_MISMATCH); } @Inject  AntiCsrfHelper(
      @Named("${nexus.security.anticsrftoken.enabled:-true}") final boolean enabled,
      @Named("${nexus.security.anticsrftoken.whitelist}") @Nullable final String whitelist); boolean isAccessAllowed(final HttpServletRequest httpRequest); void requireValidToken(final HttpServletRequest httpRequest, @Nullable final String token); boolean isEnabled(); static final String ENABLED; static final String ERROR_MESSAGE_TOKEN_MISMATCH; static final String ANTI_CSRF_TOKEN_NAME; }
@Test public void testRequireValidToken_Disabled() { underTest = new AntiCsrfHelper(false, ""); underTest.requireValidToken(httpServletRequest, "a-token"); verifyZeroInteractions(httpServletRequest); }
@Test(expected = UnauthorizedException.class) public void testRequireValidToken_Session_NoToken() { when(httpServletRequest.getHeader(HttpHeaders.USER_AGENT)).thenReturn(BROWSER_UA); underTest.requireValidToken(httpServletRequest, null); }
@Test public void testRequireValidToken_NoSessionAndNoReferrer() { underTest.requireValidToken(httpServletRequest, null); when(httpServletRequest.getHeader(HttpHeaders.USER_AGENT)).thenReturn(CLIENT_UA); try { underTest.requireValidToken(httpServletRequest, null); } catch (Exception e) { fail("expected requiring a valid token to succeed"); } }
@Test public void testRequireValidToken() { when(httpServletRequest.getHeader(HttpHeaders.USER_AGENT)).thenReturn(BROWSER_UA); when(httpServletRequest.getCookies()) .thenReturn(new Cookie[] { new Cookie(AntiCsrfHelper.ANTI_CSRF_TOKEN_NAME, "a-value") }); try { underTest.requireValidToken(httpServletRequest, "a-value"); } catch (Exception e) { fail("expected requiring a valid token to succeed"); } }
@Test(expected = UnauthorizedException.class) public void testRequireValidToken_tokenMismatch() { when(httpServletRequest.getHeader(HttpHeaders.USER_AGENT)).thenReturn(BROWSER_UA); when(httpServletRequest.getCookies()) .thenReturn(new Cookie[] { new Cookie(AntiCsrfHelper.ANTI_CSRF_TOKEN_NAME, "a-value") }); underTest.requireValidToken(httpServletRequest, "a-different-value"); }