### Question:
SessionXssNonceSetterFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpSession session = httpRequest.getSession(true); String tokenValue = (String) session.getAttribute(XSS_NONCE_ATTRIB_NAME); if (tokenValue == null) { CsrfGuard csrfGuard = CsrfGuard.getInstance(); tokenValue = RandomGenerator.generateRandomId(csrfGuard.getPrng(), csrfGuard.getTokenLength()); session.setAttribute(XSS_NONCE_ATTRIB_NAME, "nonce-" + tokenValue); } } catch (Exception e) { throw new RuntimeException(String.format("unable to generate the random XSS token - %s", e.getLocalizedMessage()), e); } chain.doFilter(request,response); }  @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void destroy(); static final String XSS_NONCE_ATTRIB_NAME; }### Answer:
@Test public void testRandomTokenIsGeneratedOncePerSession() throws Exception { filter.doFilter(requestMock, responseMock, filterChainMock); Object token1 = sessionMock.getAttribute(XSS_NONCE_ATTRIB_NAME); filter.doFilter(requestMock, responseMock, filterChainMock); Object token2 = sessionMock.getAttribute(XSS_NONCE_ATTRIB_NAME); assertNotNull("XSS Nonce is null", token1 ); assertNotNull("XSS Nonces is null", token2 ); assertTrue("XSS Nonces must be strings", token1 instanceof String && token2 instanceof String); assertEquals("XSS Nonce was generated more than once per session.", token1, token2); }
@Test public void testRandomTokensAreUniquePerSession() throws Exception { filter.doFilter(requestMock, responseMock, filterChainMock); Object token1 = sessionMock.getAttribute(XSS_NONCE_ATTRIB_NAME); sessionMock.removeAttribute(XSS_NONCE_ATTRIB_NAME); filter.doFilter(requestMock, responseMock, filterChainMock); Object token2 = sessionMock.getAttribute(XSS_NONCE_ATTRIB_NAME); assertNotNull("XSS Nonce is null", token1 ); assertNotNull("XSS Nonces is null", token2 ); assertTrue("XSS Nonces must be strings", token1 instanceof String && token2 instanceof String); assertTrue("XSS Nonces are not random", !token1.equals(token2)); }