org.eclipse.jetty.security.Authenticator Java Examples

The following examples show how to use org.eclipse.jetty.security.Authenticator. 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: HttpServer.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
protected ConstraintSecurityHandler configureCommonAuthentication(String constraintName,
    String[] allowedRoles, Authenticator authenticator, String realm,
    LoginService loginService) {

  Constraint constraint = new Constraint();
  constraint.setName(constraintName);
  constraint.setRoles(allowedRoles);
  // This is telling Jetty to not allow unauthenticated requests through (very important!)
  constraint.setAuthenticate(true);

  ConstraintMapping cm = new ConstraintMapping();
  cm.setConstraint(constraint);
  cm.setPathSpec("/*");

  ConstraintSecurityHandler sh = new ConstraintSecurityHandler();
  sh.setAuthenticator(authenticator);
  sh.setLoginService(loginService);
  sh.setConstraintMappings(new ConstraintMapping[]{cm});
  sh.setRealmName(realm);

  return sh;
}
 
Example #2
Source File: AbstractJettyAppServerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testDetectingOIDC() throws Exception {
    // given
    URL webXml = AbstractJettyAppServerTest.class.getResource("/web-oidc.xml");
    WebArchive archive = ShrinkWrap.create(WebArchive.class,"archive.war")
            .addAsWebInfResource(webXml, "web.xml");

    JettyAppServer server = new JettyAppServer();

    // when
    Authenticator installedAuthenticator = null;
    try {
        server.start();
        server.deploy(archive);

        installedAuthenticator = server.getServer()
                .getBean(DeploymentManager.class).getApps().iterator().next()
                .getContextHandler().getChildHandlerByClass(SecurityHandler.class).getAuthenticator();
    } finally {
        server.stop();
    }

    // assert
    Assert.assertTrue(installedAuthenticator instanceof KeycloakJettyAuthenticator);
}
 
Example #3
Source File: AbstractJettyAppServerTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testDetectingSAML() throws Exception {
    // given
    URL webXml = AbstractJettyAppServerTest.class.getResource("/web-saml.xml");
    WebArchive archive = ShrinkWrap.create(WebArchive.class,"archive.war")
            .addAsWebInfResource(webXml, "web.xml");

    JettyAppServer server = new JettyAppServer();

    // when
    Authenticator installedAuthenticator = null;
    try {
        server.start();
        server.deploy(archive);

        installedAuthenticator = server.getServer()
                .getBean(DeploymentManager.class).getApps().iterator().next()
                .getContextHandler().getChildHandlerByClass(SecurityHandler.class).getAuthenticator();
    } finally {
        server.stop();
    }

    // assert
    Assert.assertTrue(installedAuthenticator instanceof KeycloakSamlAuthenticator);
}
 
Example #4
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 #5
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 #6
Source File: JwtAuthenticatorTest.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testSuccessfulLogin() throws Exception {
  UserStore testUserStore = new UserStore();
  testUserStore.addUser(TEST_USER, SecurityUtils.NO_CREDENTIAL, new String[]{USER_ROLE});
  TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER);
  JwtLoginService loginService = new JwtLoginService(new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), null);

  Authenticator.AuthConfiguration configuration = mock(Authenticator.AuthConfiguration.class);
  expect(configuration.getLoginService()).andReturn(loginService);
  expect(configuration.getIdentityService()).andReturn(new DefaultIdentityService());
  expect(configuration.isSessionRenewedOnAuthentication()).andReturn(true);

  Request request = niceMock(Request.class);
  expect(request.getMethod()).andReturn(HttpMethod.GET.asString());
  expect(request.getHeader(HttpHeader.AUTHORIZATION.asString())).andReturn(null);
  request.setAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE, tokenAndKeys.token());
  expectLastCall().andVoid();
  expect(request.getCookies()).andReturn(new Cookie[] {new Cookie(JWT_TOKEN, tokenAndKeys.token())});
  expect(request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE)).andReturn(tokenAndKeys.token());

  HttpServletResponse response = mock(HttpServletResponse.class);

  replay(configuration, request, response);
  JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN);
  authenticator.setConfiguration(configuration);
  UserAuthentication authentication = (UserAuthentication) authenticator.validateRequest(request, response, true);
  verify(configuration, request, response);

  assertNotNull(authentication);
  assertTrue(authentication.getUserIdentity().getUserPrincipal() instanceof JwtUserPrincipal);
  JwtUserPrincipal userPrincipal = (JwtUserPrincipal) authentication.getUserIdentity().getUserPrincipal();
  assertEquals(TEST_USER, userPrincipal.getName());
  assertEquals(tokenAndKeys.token(), userPrincipal.getSerializedToken());
}
 
Example #7
Source File: JwtAuthenticatorTest.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testFailedLoginWithUserNotFound() throws Exception {
  UserStore testUserStore = new UserStore();
  testUserStore.addUser(TEST_USER_2, SecurityUtils.NO_CREDENTIAL, new String[] {USER_ROLE});
  TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER);
  JwtLoginService loginService = new JwtLoginService(new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), null);

  Authenticator.AuthConfiguration configuration = mock(Authenticator.AuthConfiguration.class);
  expect(configuration.getLoginService()).andReturn(loginService);
  expect(configuration.getIdentityService()).andReturn(new DefaultIdentityService());
  expect(configuration.isSessionRenewedOnAuthentication()).andReturn(true);

  Request request = niceMock(Request.class);
  expect(request.getMethod()).andReturn(HttpMethod.GET.asString());
  expect(request.getHeader(HttpHeader.AUTHORIZATION.asString())).andReturn(null);
  request.setAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE, tokenAndKeys.token());
  expectLastCall().andVoid();
  expect(request.getCookies()).andReturn(new Cookie[] {new Cookie(JWT_TOKEN, tokenAndKeys.token())});
  expect(request.getAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE)).andReturn(tokenAndKeys.token());

  HttpServletResponse response = mock(HttpServletResponse.class);
  response.setStatus(HttpStatus.UNAUTHORIZED_401);
  expectLastCall().andVoid();

  replay(configuration, request, response);
  JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN);
  authenticator.setConfiguration(configuration);
  Authentication authentication = authenticator.validateRequest(request, response, true);
  verify(configuration, request, response);

  assertNotNull(authentication);
  assertEquals(Authentication.SEND_FAILURE, authentication);
}
 
Example #8
Source File: JwtAuthenticatorTest.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void testFailedLoginWithInvalidToken() throws Exception {
  UserStore testUserStore = new UserStore();
  testUserStore.addUser(TEST_USER_2, SecurityUtils.NO_CREDENTIAL, new String[] {USER_ROLE});
  TokenGenerator.TokenAndKeys tokenAndKeys = TokenGenerator.generateToken(TEST_USER);
  TokenGenerator.TokenAndKeys tokenAndKeys2 = TokenGenerator.generateToken(TEST_USER);
  JwtLoginService loginService = new JwtLoginService(new UserStoreAuthorizationService(testUserStore), tokenAndKeys.publicKey(), null);

  Authenticator.AuthConfiguration configuration = mock(Authenticator.AuthConfiguration.class);
  expect(configuration.getLoginService()).andReturn(loginService);
  expect(configuration.getIdentityService()).andReturn(new DefaultIdentityService());
  expect(configuration.isSessionRenewedOnAuthentication()).andReturn(true);

  Request request = niceMock(Request.class);
  expect(request.getMethod()).andReturn(HttpMethod.GET.asString());
  expect(request.getHeader(HttpHeader.AUTHORIZATION.asString())).andReturn(null);
  request.setAttribute(JwtAuthenticator.JWT_TOKEN_REQUEST_ATTRIBUTE, tokenAndKeys2.token());
  expectLastCall().andVoid();
  expect(request.getCookies()).andReturn(new Cookie[] {new Cookie(JWT_TOKEN, tokenAndKeys2.token())});

  HttpServletResponse response = mock(HttpServletResponse.class);
  response.setStatus(HttpStatus.UNAUTHORIZED_401);
  expectLastCall().andVoid();

  replay(configuration, request, response);
  JwtAuthenticator authenticator = new JwtAuthenticator(TOKEN_PROVIDER, JWT_TOKEN);
  authenticator.setConfiguration(configuration);
  Authentication authentication = authenticator.validateRequest(request, response, true);
  verify(configuration, request, response);

  assertNotNull(authentication);
  assertEquals(Authentication.SEND_FAILURE, authentication);
}
 
Example #9
Source File: TestActivationAuthenticator.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidateRequestDelegationNotEnabled() throws Exception {
  Authenticator auth = Mockito.mock(Authenticator.class);
  Activation activation = Mockito.mock(Activation.class);
  ActivationAuthenticator activationAuth = new ActivationAuthenticator(auth, activation);

  ServletRequest req = Mockito.mock(ServletRequest.class);
  ServletResponse res = Mockito.mock(ServletResponse.class);
  Authentication authResponse = Mockito.mock(Authentication.class);

  Mockito.when(auth.validateRequest(Mockito.eq(req), Mockito.eq(res), Mockito.eq(false))).thenReturn(authResponse);

  // test not user, activation not enabled
  Mockito.when(activation.isEnabled()).thenReturn(false);
  Assert.assertEquals(authResponse, activationAuth.validateRequest(req, res, false));

  // test not user, activation enabled
  Mockito.when(activation.isEnabled()).thenReturn(true);
  Assert.assertEquals(authResponse, activationAuth.validateRequest(req, res, false));

  // test user, activation not enabled
  authResponse = Mockito.mock(Authentication.User.class);
  Mockito.when(auth.validateRequest(Mockito.eq(req), Mockito.eq(res), Mockito.eq(false))).thenReturn(authResponse);
  Mockito.when(activation.isEnabled()).thenReturn(false);
  Assert.assertEquals(authResponse, activationAuth.validateRequest(req, res, false));

  // test user, activation enabled, activation not expired
  Mockito.when(activation.isEnabled()).thenReturn(true);
  Activation.Info info = Mockito.mock(Activation.Info.class);
  Mockito.when(info.isValid()).thenReturn(true);
  Mockito.when(activation.getInfo()).thenReturn(info);
  Assert.assertEquals(authResponse, activationAuth.validateRequest(req, res, false));

  // test user, activation enabled, activation expired
  Mockito.when(info.isValid()).thenReturn(false);
  Authentication authResponseGot = activationAuth.validateRequest(req, res, false);
  Assert.assertTrue(authResponseGot instanceof ActivationAuthenticator.ExpiredActivationUser);
}
 
Example #10
Source File: AuthenticationIntegrationTest.java    From cruise-control with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public Authenticator authenticator() {
  return new BasicAuthenticator();
}
 
Example #11
Source File: BasicSecurityProvider.java    From cruise-control with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public Authenticator authenticator() {
  return new BasicAuthenticator();
}
 
Example #12
Source File: HttpConductorImpl.java    From sql-layer with GNU Affero General Public License v3.0 4 votes vote down vote up
public Authenticator createAuthenticator() throws IllegalAccessException, InstantiationException {
    return authenticatorClass.newInstance();
}
 
Example #13
Source File: HttpConductorImpl.java    From sql-layer with GNU Affero General Public License v3.0 4 votes vote down vote up
private AuthenticationType(CredentialType credentialType, Class<? extends Authenticator> authenticatorClass) {
    this.credentialType = credentialType;
    this.authenticatorClass = authenticatorClass;
}
 
Example #14
Source File: SpnegoSecurityProvider.java    From cruise-control with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public Authenticator authenticator() {
  return new ConfigurableSpnegoAuthenticator();
}
 
Example #15
Source File: ActivationAuthenticator.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public ActivationAuthenticator(Authenticator authenticator, Activation activation) {
  Utils.checkNotNull(authenticator, "authenticator");
  Utils.checkNotNull(activation, "activation");
  this.authenticator = authenticator;
  this.activation = activation;
}
 
Example #16
Source File: WebServerTask.java    From datacollector with Apache License 2.0 4 votes vote down vote up
protected Authenticator injectActivationCheck(Authenticator authenticator) {
  return (activation == null) ? authenticator : new ActivationAuthenticator(authenticator, activation);
}
 
Example #17
Source File: JwtSecurityProvider.java    From cruise-control with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public Authenticator authenticator() {
  return new JwtAuthenticator(_authenticationProviderUrl, _cookieName);
}
 
Example #18
Source File: TrustedProxySecurityProvider.java    From cruise-control with BSD 2-Clause "Simplified" License 4 votes vote down vote up
@Override
public Authenticator authenticator() {
  return new ConfigurableSpnegoAuthenticator();
}
 
Example #19
Source File: SecurityProvider.java    From cruise-control with BSD 2-Clause "Simplified" License 2 votes vote down vote up
/**
 * Defines the request authentication method which is responsible to send challenges
 * according to authentication method and decide if the user has valid credentials according
 * to the authentication method.
 *
 * @throws ServletException if any problem occurred during the initialization of the Authenticator.
 * @return the {@link Authenticator} that'll be used for checking the incoming requests.
 */
Authenticator authenticator() throws ServletException;