org.eclipse.jetty.server.Authentication Java Examples

The following examples show how to use org.eclipse.jetty.server.Authentication. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SSOUserAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
Authentication redirectToLogin(HttpServletRequest httpReq, HttpServletResponse httpRes) throws ServerAuthException {
  boolean repeatedRedirect = httpReq.getParameter(SSOConstants.REPEATED_REDIRECT_PARAM) != null;
  String urlToLogin = getLoginUrl(httpReq, repeatedRedirect);
  try {
    LOG.debug("Redirecting to login '{}'", urlToLogin);
    if (doMetaRedirectToSso) {
      httpRes.setContentType("text/html");
      httpRes.setStatus(HttpServletResponse.SC_OK);
      httpRes.getWriter().println(String.format(HTML_META_REDIRECT, urlToLogin));
    } else {
      httpRes.sendRedirect(urlToLogin);
    }
    return Authentication.SEND_CONTINUE;
  } catch (IOException ex) {
    throw new ServerAuthException(Utils.format("Could not redirect to '{}': {}", urlToLogin, ex.toString(), ex));
  }
}
 
Example #2
Source File: TestSSOAppAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateRequestMandatoryNoRESTCall() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOAppAuthenticator authenticator = Mockito.spy(new SSOAppAuthenticator(ssoService));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_APP_COMPONENT_ID))).thenReturn("componentId");
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_REST_CALL))).thenReturn(null);
  Mockito
      .doReturn(Authentication.SEND_FAILURE)
      .when(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.eq("componentId"), Mockito.anyString());
  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.validateRequest(req, res, true));
  Mockito
      .verify(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.eq("componentId"), Mockito.anyString());
}
 
Example #3
Source File: TestSSOAppAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateRequestMandatoryNoAuthToken() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOAppAuthenticator authenticator = Mockito.spy(new SSOAppAuthenticator(ssoService));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_APP_COMPONENT_ID))).thenReturn("componentId");
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_REST_CALL))).thenReturn("foo");
  Mockito
      .doReturn(Authentication.SEND_FAILURE)
      .when(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.eq("componentId"), Mockito.anyString());
  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.validateRequest(req, res, true));
  Mockito
      .verify(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.eq("componentId"), Mockito.anyString());
}
 
Example #4
Source File: SpnegoAuthenticatorEx.java    From sql-layer with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Authentication validateRequest(ServletRequest request, ServletResponse response, boolean mandatory) throws ServerAuthException {
    Authentication result = super.validateRequest(request, response, mandatory);
    if ((result == Authentication.UNAUTHENTICATED) &&
        mandatory &&
        !DeferredAuthentication.isDeferred((HttpServletResponse)response)) {
        LOG.debug("SpengoAuthenticatorEx: unauthenticated -> forbidden");
        try {
            ((HttpServletResponse)response).sendError(Response.SC_FORBIDDEN,
                                                      "negotiation failure");
        }
        catch (IOException ex) {
            throw new ServerAuthException(ex);
        }
        result = Authentication.SEND_FAILURE;
    }
    return result;
}
 
Example #5
Source File: TestSSOAppAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateRequestMandatoryNoComponentIdToken() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOAppAuthenticator authenticator = Mockito.spy(new SSOAppAuthenticator(ssoService));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_APP_AUTH_TOKEN))).thenReturn("token");
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_REST_CALL))).thenReturn("foo");
  Mockito
      .doReturn(Authentication.SEND_FAILURE)
      .when(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.anyString(), Mockito.anyString());
  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.validateRequest(req, res, true));
  Mockito
      .verify(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.anyString(), Mockito.anyString());
}
 
Example #6
Source File: TestSSOAppAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateRequestMandatoryInvalidToken() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOAppAuthenticator authenticator = Mockito.spy(new SSOAppAuthenticator(ssoService));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_APP_AUTH_TOKEN))).thenReturn("token");
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_APP_COMPONENT_ID))).thenReturn("componentId");
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_REST_CALL))).thenReturn("foo");
  Mockito.when(ssoService.validateAppToken(Mockito.eq("token"), Mockito.eq("componentId"))).thenReturn(null);
  Mockito
      .doReturn(Authentication.SEND_FAILURE)
      .when(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.anyString(), Mockito.anyString());
  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.validateRequest(req, res, true));
  Mockito
      .verify(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.anyString(), Mockito.anyString());
  Mockito.verify(ssoService, Mockito.times(1)).validateAppToken(Mockito.eq("token"), Mockito.eq("componentId"));
}
 
Example #7
Source File: CustomAuthHttpServerTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Override public RemoteUserExtractor getRemoteUserExtractor() {
  return new RemoteUserExtractor() {
    @Override public String extract(HttpServletRequest request)
        throws RemoteUserExtractionException {
      methodCallCounter3++;
      if (request instanceof Request) {
        Authentication authentication = ((Request) request).getAuthentication();
        if (authentication instanceof UserAuthentication) {
          UserIdentity userIdentity = ((UserAuthentication) authentication).getUserIdentity();
          return userIdentity.getUserPrincipal().getName();
        }
      }
      throw new RemoteUserExtractionException("Request doesn't contain user credentials.");
    }
  };
}
 
Example #8
Source File: TestSSOAppAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateRequestMandatoryValidToken() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOAppAuthenticator authenticator = Mockito.spy(new SSOAppAuthenticator(ssoService));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_APP_AUTH_TOKEN))).thenReturn("token");
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_APP_COMPONENT_ID))).thenReturn("componentId");
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_REST_CALL))).thenReturn("foo");
  Mockito.when(ssoService.validateAppToken(Mockito.eq("token"), Mockito.eq("componentId"))).thenReturn(null);
  SSOPrincipal principal = Mockito.mock(SSOPrincipal.class);
  Mockito.when(principal.getTokenStr()).thenReturn("token");
  Mockito.when(principal.getExpires()).thenReturn(1L);
  Mockito.doReturn(principal).when(ssoService).validateAppToken(Mockito.eq("token"), Mockito.eq("componentId"));

  Authentication auth = authenticator.validateRequest(req, res, true);
  Assert.assertNotNull(auth);
  Assert.assertSame(principal, ((SSOAuthenticationUser)auth).getSSOUserPrincipal());
}
 
Example #9
Source File: ActivationAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
public Authentication validateRequest(
    ServletRequest request, ServletResponse response, boolean mandatory
) throws ServerAuthException {
  Authentication authentication = authenticator.validateRequest(request, response, mandatory);
  if (authentication instanceof Authentication.User) {
    Activation.Info activationInfo = activation.getInfo();
    if (activation.isEnabled() && !activationInfo.isValid()) {
      boolean hasTrial = activationInfo.getExpiration() > 0;
      authentication = new ExpiredActivationUser(
          (Authentication.User) authentication,
          hasTrial ? TRIAL_ALLOWED_ROLES : NO_TRIAL_ALLOWED_ROLES
      );
    }
  }
  return authentication;
}
 
Example #10
Source File: AvaticaSpnegoAuthenticator.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
/**
 * Jetty has a bug in which if there is an Authorization header sent by a client which is
 * not of the Negotiate type, Jetty does not send the challenge to negotiate. This works
 * around that issue, forcing the challenge to be sent. Will require investigation on
 * upgrade to a newer version of Jetty.
 */
Authentication sendChallengeIfNecessary(Authentication computedAuth, ServletRequest request,
    ServletResponse response) throws IOException {
  if (computedAuth == Authentication.UNAUTHENTICATED) {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    String header = req.getHeader(HttpHeader.AUTHORIZATION.asString());
    // We have an authorization header, but it's not Negotiate
    if (header != null && !header.startsWith(HttpHeader.NEGOTIATE.asString())) {
      LOG.debug("Client sent Authorization header that was not for Negotiate,"
          + " sending challenge anyways.");
      if (DeferredAuthentication.isDeferred(res)) {
        return Authentication.UNAUTHENTICATED;
      }

      res.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), HttpHeader.NEGOTIATE.asString());
      res.sendError(HttpServletResponse.SC_UNAUTHORIZED);
      return Authentication.SEND_CONTINUE;
    }
  }
  return computedAuth;
}
 
Example #11
Source File: TestSSOUserAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateRequestMandatoryInvalidAuthToken() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOUserAuthenticator authenticator = Mockito.spy(new SSOUserAuthenticator(ssoService, conf));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.doReturn("token").when(authenticator).getAuthTokenFromRequest(Mockito.eq(req));

  Mockito.doReturn(Authentication.SEND_FAILURE).when(authenticator).returnUnauthorized(Mockito.eq(req), Mockito.eq
      (res), Mockito.anyString(), Mockito.anyString());

  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.validateRequest(req, res, true));
  Mockito
      .verify(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.anyString(), Mockito.anyString());
  Mockito.verify(ssoService).validateUserToken(Mockito.eq("token"));
  Mockito.verifyNoMoreInteractions(ssoService);
}
 
Example #12
Source File: TestActivationAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testCleanDelegationMethods() throws Exception {
  Authenticator auth = Mockito.mock(Authenticator.class);
  Activation activation = Mockito.mock(Activation.class);
  ActivationAuthenticator activationAuth = new ActivationAuthenticator(auth, activation);

  Authenticator.AuthConfiguration conf = Mockito.mock(Authenticator.AuthConfiguration.class);
  activationAuth.setConfiguration(conf);
  Mockito.verify(auth, Mockito.times(1)).setConfiguration(Mockito.eq(conf));

  Mockito.when(auth.getAuthMethod()).thenReturn("foo");
  Assert.assertEquals("foo", activationAuth.getAuthMethod());

  ServletRequest req = Mockito.mock(ServletRequest.class);
  activationAuth.prepareRequest(req);
  Mockito.verify(auth, Mockito.times(1)).prepareRequest(Mockito.eq(req));

  ServletResponse res = Mockito.mock(ServletResponse.class);
  Authentication.User user = Mockito.mock(Authentication.User.class);
  Mockito.when(auth.secureResponse(Mockito.eq(req), Mockito.eq(res), Mockito.eq(true), Mockito.eq(user)))
         .thenReturn(true);
  Assert.assertTrue(auth.secureResponse(req, res, true, user));
}
 
Example #13
Source File: JwtAuthenticatorTest.java    From cruise-control with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testRedirect() throws IOException, ServerAuthException {
  JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN);

  HttpServletRequest request = mock(HttpServletRequest.class);
  expect(request.getMethod()).andReturn(HttpMethod.GET.asString());
  expect(request.getQueryString()).andReturn(null);
  expect(request.getHeader(HttpHeader.AUTHORIZATION.asString())).andReturn(null);
  expect(request.getCookies()).andReturn(new Cookie[] {});
  expect(request.getRequestURL()).andReturn(new StringBuffer(CRUISE_CONTROL_ENDPOINT));

  HttpServletResponse response = mock(HttpServletResponse.class);
  response.sendRedirect(TOKEN_PROVIDER.replace(JwtAuthenticator.REDIRECT_URL, CRUISE_CONTROL_ENDPOINT));
  expectLastCall().andVoid();

  replay(request, response);
  Authentication actualAuthentication = authenticator.validateRequest(request, response, true);
  verify(request, response);
  assertEquals(Authentication.SEND_CONTINUE, actualAuthentication);
}
 
Example #14
Source File: FederationAuthenticator.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private Authentication handleSignOutCleanup(HttpServletResponse response, HttpSession session) throws IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("SignOutCleanup request found");
        LOG.debug("SignOutCleanup action...");
    }
    session.invalidate();

    final ServletOutputStream responseOutputStream = response.getOutputStream();
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("logout.jpg");
    if (inputStream == null) {
        LOG.warn("Could not write logout.jpg");
        return Authentication.SEND_FAILURE;
    }
    int read = 0;
    byte[] buf = new byte[1024];
    while ((read = inputStream.read(buf)) != -1) {
        responseOutputStream.write(buf, 0, read);
    }
    inputStream.close();
    responseOutputStream.flush();
    return Authentication.SEND_SUCCESS;
}
 
Example #15
Source File: TestInvokeHttpCommon.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse
        response)throws IOException, ServletException {
    baseRequest.setHandled(true);

    try {
        Authentication authentication = digestAuthenticator.validateRequest(request, response, true);

        if (authentication instanceof Authentication.User) {
            response.setContentType("text/plain");
            Authentication.User user = (Authentication.User) authentication;
            response.getWriter().println(user.getAuthMethod());
        } else if (authentication instanceof Authentication.ResponseSent) {
            Authentication.ResponseSent responseSent = (Authentication.ResponseSent) authentication;
        }
    } catch (ServerAuthException e) {
        e.printStackTrace();
    }
}
 
Example #16
Source File: TestInvokeHttpCommon.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse
        response)throws IOException, ServletException {
    baseRequest.setHandled(true);

    try {
        Authentication authentication = digestAuthenticator.validateRequest(request, response, true);

        if (authentication instanceof Authentication.User) {
            response.setContentType("text/plain");
            Authentication.User user = (Authentication.User) authentication;
            response.getWriter().println(user.getAuthMethod());
        } else if (authentication instanceof Authentication.ResponseSent) {
            Authentication.ResponseSent responseSent = (Authentication.ResponseSent) authentication;
        }
    } catch (ServerAuthException e) {
        e.printStackTrace();
    }
}
 
Example #17
Source File: TestSSOUserAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testreturnUnauthorizedREST() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOUserAuthenticator authenticator = Mockito.spy(new SSOUserAuthenticator(ssoService, conf));
  Mockito
      .doReturn("http://foo")
      .when(authenticator)
      .getLoginUrl(Mockito.any(HttpServletRequest.class), Mockito.anyBoolean());

  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  Mockito.when(req.getHeader(Mockito.eq(SSOConstants.X_REST_CALL))).thenReturn("foo");
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.when(res.getWriter()).thenReturn(new PrintWriter(new StringWriter()));
  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.returnUnauthorized(req, res, "principal", "template"));
  Mockito.verify(res).setContentType(Mockito.eq("application/json"));
}
 
Example #18
Source File: AbstractSSOAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
protected Authentication returnUnauthorized(
    HttpServletRequest httpReq,
    HttpServletResponse httpRes,
    Map errorReason,
    String principalId,
    String logMessageTemplate
) throws ServerAuthException {
  if (getLog().isDebugEnabled()) {
    getLog().debug(logMessageTemplate, getRequestInfoForLogging(httpReq, principalId));
  }
  try {
    httpRes.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "dpm");
    httpRes.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    httpRes.setContentType("application/json");
    OBJECT_MAPPER.writeValue(httpRes.getWriter(), errorReason);
    return Authentication.SEND_FAILURE;
  } catch (IOException ex) {
    throw new ServerAuthException(Utils.format("Could send a Unauthorized (401) response: {}", ex.toString(), ex));
  }
}
 
Example #19
Source File: TestSSOUserAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testreturnUnauthorized() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  ssoService.setConfiguration(new Configuration());
  SSOUserAuthenticator authenticator = Mockito.spy(new SSOUserAuthenticator(ssoService, conf));
  Mockito
      .doReturn("http://foo")
      .when(authenticator)
      .getLoginUrl(Mockito.any(HttpServletRequest.class), Mockito.anyBoolean());

  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  Mockito.when(req.getServerPort()).thenReturn(1000);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.when(res.getWriter()).thenReturn(new PrintWriter(new StringWriter()));
  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.returnUnauthorized(req, res, "principal", "template"));
  Mockito.verify(authenticator).redirectToLogin(Mockito.eq(req), Mockito.eq(res));
  ArgumentCaptor<Cookie> cookieCaptor = ArgumentCaptor.forClass(Cookie.class);
  Mockito.verify(authenticator, Mockito.times(1)).createAuthCookie(Mockito.eq(req), Mockito.eq(""), Mockito.eq(0L));
  Mockito.verify(res, Mockito.times(1)).addCookie(cookieCaptor.capture());
  Assert.assertEquals(authenticator.getAuthCookieName(req), cookieCaptor.getValue().getName());
  Assert.assertEquals("", cookieCaptor.getValue().getValue());
  Assert.assertEquals("/", cookieCaptor.getValue().getPath());
  Assert.assertEquals(0, cookieCaptor.getValue().getMaxAge());
}
 
Example #20
Source File: TestAbstractSSOAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testReturnForbidden() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  AbstractSSOAuthenticator authenticator = new ForTestSSOAuthenticator(ssoService);

  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  Mockito.when(req.getRequestURL()).thenReturn(new StringBuffer("url"));
  Mockito.when(req.getRemoteAddr()).thenReturn("remoteAddress");
  Mockito.when(req.getMethod()).thenReturn("method");
  Mockito.when(req.getQueryString()).thenReturn("QS");

  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  StringWriter writer = new StringWriter();
  PrintWriter printWriter = new PrintWriter(writer);
  Mockito.when(res.getWriter()).thenReturn(printWriter);

  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.returnUnauthorized(req, res, "principal", "template"));

  ArgumentCaptor<Integer> error = ArgumentCaptor.forClass(Integer.class);
  Mockito.verify(res).setStatus(error.capture());
  Assert.assertEquals(
      SSOUserAuthenticator.UNAUTHORIZED_JSON,
      new ObjectMapper().readValue(writer.toString().trim(), Map.class)
  );
  Mockito.verify(res).setContentType(Mockito.eq("application/json"));
}
 
Example #21
Source File: TestSSOUserAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testRedirectToSelf() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOUserAuthenticator authenticator = new SSOUserAuthenticator(ssoService, conf);

  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  Mockito.when(req.getRequestURL()).thenReturn(new StringBuffer("http://foo/bar"));
  Mockito.when(req.getQueryString()).thenReturn("a=A&b=B&" + SSOConstants.USER_AUTH_TOKEN_PARAM + "=token");

  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);

  Assert.assertEquals(Authentication.SEND_CONTINUE, authenticator.redirectToSelf(req, res));
  ArgumentCaptor<String> redirect = ArgumentCaptor.forClass(String.class);
  Mockito.verify(res).sendRedirect(redirect.capture());
  Assert.assertEquals("http://foo/bar?a=A&b=B", redirect.getValue());
}
 
Example #22
Source File: SSOAuthenticator.java    From datacollector with Apache License 2.0 6 votes vote down vote up
Authentication validateRequestDelegation(ServletRequest request, ServletResponse response, boolean mandatory)
    throws ServerAuthException {
  Authenticator auth = userAuthenticator;
  HttpServletRequest httpReq = (HttpServletRequest) request;
  boolean isRestCall = httpReq.getHeader(SSOConstants.X_REST_CALL) != null;
  boolean isAppCall = httpReq.getHeader(SSOConstants.X_APP_AUTH_TOKEN) != null ||
      httpReq.getHeader(SSOConstants.X_APP_COMPONENT_ID) != null;
  if (isAppCall && isRestCall) {
    auth = appAuthenticator;
    if (getLog().isTraceEnabled()) {
      getLog().trace("App request '{}'", getRequestInfoForLogging(httpReq, "?"));
    }
  } else {
    if (getLog().isTraceEnabled()) {
      getLog().trace("User request '{}'", getRequestInfoForLogging(httpReq, "?"));
    }
  }
  return auth.validateRequest(request, response, mandatory);
}
 
Example #23
Source File: KeycloakJettyAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected Authentication createAuthentication(UserIdentity userIdentity, Request request) {
    return new KeycloakAuthentication(getAuthMethod(), userIdentity) {
        @Override
        public void logout() {
            logoutCurrent(HttpChannel.getCurrentHttpChannel().getRequest());
        }
    };
}
 
Example #24
Source File: KeycloakJettyAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected Authentication createAuthentication(UserIdentity userIdentity, final Request request) {
    return new KeycloakAuthentication(getAuthMethod(), userIdentity) {
        @Override
        public void logout() {
            logoutCurrent(request);
        }
    };
}
 
Example #25
Source File: AbstractKeycloakJettyAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected Authentication register(Request request, KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal) {
    request.setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext);
    Authentication authentication = request.getAuthentication();
    if (!(authentication instanceof KeycloakAuthentication)) {
        UserIdentity userIdentity = createIdentity(principal);
        authentication = createAuthentication(userIdentity, request);
        request.setAuthentication(authentication);
    }
    return authentication;
}
 
Example #26
Source File: TestSSOUserAuthenticator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testRedirectToLogout() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  Mockito.when(ssoService.getLogoutUrl()).thenReturn("http://foo/logout");
  SSOUserAuthenticator authenticator = new SSOUserAuthenticator(ssoService, conf);

  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Authentication auth = authenticator.redirectToLogout(res);
  Assert.assertEquals(Authentication.SEND_SUCCESS, auth);
  Mockito.verify(res).sendRedirect(Mockito.eq(ssoService.getLogoutUrl()));
}
 
Example #27
Source File: TestSSOUserAuthenticator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateRequestMandatoryValidAuthToken() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOUserAuthenticator authenticator = Mockito.spy(new SSOUserAuthenticator(ssoService, conf));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.doReturn("token").when(authenticator).getAuthTokenFromRequest(Mockito.eq(req));
  SSOPrincipal principal = Mockito.mock(SSOPrincipal.class);
  Mockito.when(principal.getTokenStr()).thenReturn("token");
  Mockito.when(principal.getExpires()).thenReturn(1L);
  Mockito.doReturn(principal).when(ssoService).validateUserToken(Mockito.eq("token"));

  Mockito.doReturn(false).when(authenticator).isLogoutRequest(Mockito.eq(req));
  Mockito.doNothing().when(authenticator).setAuthCookieIfNecessary(Mockito.eq(req), Mockito.eq(res), Mockito.eq
      ("token"), Mockito.eq(1));
  Mockito.doReturn(false).when(authenticator).isAuthTokenInQueryString(Mockito.eq(req));

  Authentication auth = authenticator.validateRequest(req, res, true);
  Assert.assertNotNull(auth);
  Assert.assertSame(principal, ((SSOAuthenticationUser)auth).getSSOUserPrincipal());

  Mockito.verify(authenticator).isLogoutRequest(Mockito.eq(req));
  Mockito
      .verify(authenticator)
      .setAuthCookieIfNecessary(Mockito.eq(req), Mockito.eq(res), Mockito.eq("token"), Mockito.eq(1L));
  Mockito.verify(authenticator).isAuthTokenInQueryString(Mockito.eq(req));

  Mockito.verify(ssoService).validateUserToken(Mockito.eq("token"));
  Mockito.verifyNoMoreInteractions(ssoService);
}
 
Example #28
Source File: TestSSOUserAuthenticator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateRequestMandatoryNoAuthToken() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOUserAuthenticator authenticator = Mockito.spy(new SSOUserAuthenticator(ssoService, conf));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);
  Mockito.doReturn(Authentication.SEND_FAILURE).when(authenticator).returnUnauthorized(Mockito.eq(req), Mockito.eq
      (res), Mockito.anyString(), Mockito.anyString());

  Assert.assertEquals(Authentication.SEND_FAILURE, authenticator.validateRequest(req, res, true));
  Mockito
      .verify(authenticator)
      .returnUnauthorized(Mockito.eq(req), Mockito.eq(res), Mockito.anyString(), Mockito.anyString());
  Mockito.verifyNoMoreInteractions(ssoService);
}
 
Example #29
Source File: TestSSOUserAuthenticator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateRequestNotMandatory() throws Exception {
  SSOService ssoService = Mockito.mock(SSOService.class);
  SSOUserAuthenticator authenticator = Mockito.spy(new SSOUserAuthenticator(ssoService, conf));
  HttpServletRequest req = Mockito.mock(HttpServletRequest.class);
  HttpServletResponse res = Mockito.mock(HttpServletResponse.class);

  Assert.assertEquals(Authentication.NOT_CHECKED, authenticator.validateRequest(req, res, false));
}
 
Example #30
Source File: DrillSpnegoAuthenticator.java    From Bats with Apache License 2.0 5 votes vote down vote up
public UserIdentity login(String username, Object password, ServletRequest request) {
  final UserIdentity user = super.login(username, password, request);

  if (user != null) {
    final HttpSession session = ((HttpServletRequest) request).getSession(true);
    final Authentication cached = new SessionAuthentication(this.getAuthMethod(), user, password);
    session.setAttribute(SessionAuthentication.__J_AUTHENTICATED, cached);
  }

  return user;
}