UserAuthFactory { public User provide(ContainerRequest request) { Cookie sessionCookie = request.getCookies().get(sessionCookieName); if (sessionCookie == null) { logger.warn("No session cookie in request."); throw new NotAuthorizedException("Bad session"); } try { return authenticator.authenticate(sessionCookie) .orElseThrow(() -> new NotAuthorizedException("Bad session")); } catch (AuthenticationException e) { throw Throwables.propagate(e); } } @Inject  UserAuthFactory(CookieAuthenticator cookieAuthenticator,
      @SessionCookie CookieConfig cookieConfig); User provide(ContainerRequest request);  }
@Test(expected = NotAuthorizedException.class) public void noSessionCookie() throws Exception { cookies.put("not-session", new Cookie("not-session", "value")); factory.provide(request); }
@Test(expected = NotAuthorizedException.class) public void invalidSessionCookie() throws Exception { Cookie badSessionCookie = new Cookie("session", "bad-value"); cookies.put(badSessionCookie.getName(), badSessionCookie); when(cookieAuthenticator.authenticate(badSessionCookie)).thenReturn(Optional.empty()); factory.provide(request); }
@Test public void successfulAuth() throws Exception { User user = User.named("username"); Cookie sessionCookie = new Cookie("session", "valid-session"); cookies.put(sessionCookie.getName(), sessionCookie); when(cookieAuthenticator.authenticate(sessionCookie)).thenReturn(Optional.of(user)); assertThat(factory.provide(request)).isEqualTo(user); }