/**
  * Load user's info from database.
  *
  * @param userName
  */
 @Override
 protected UserIdentity loadUser(String userName) {
   try {
     try (Connection connection = getConnection();
         PreparedStatement statement1 = connection.prepareStatement(_userSql)) {
       statement1.setObject(1, userName);
       try (ResultSet rs1 = statement1.executeQuery()) {
         if (rs1.next()) {
           int key = rs1.getInt(_userTableKey);
           String credentials = rs1.getString(_userTablePasswordField);
           List<String> roles = new ArrayList<String>();
           try (PreparedStatement statement2 = connection.prepareStatement(_roleSql)) {
             statement2.setInt(1, key);
             try (ResultSet rs2 = statement2.executeQuery()) {
               while (rs2.next()) {
                 roles.add(rs2.getString(_roleTableRoleField));
               }
             }
           }
           return putUser(
               userName,
               Credential.getCredential(credentials),
               roles.toArray(new String[roles.size()]));
         }
       }
     }
   } catch (NamingException e) {
     LOG.warn("No datasource for " + _jndiName, e);
   } catch (SQLException e) {
     LOG.warn("Problem loading user info for " + userName, e);
   }
   return null;
 }
  /* ------------------------------------------------------------ */
  @Override
  protected UserIdentity loadUser(String username) {
    try {
      if (null == _con) connectDatabase();

      if (null == _con) throw new SQLException("Can't connect to database");

      PreparedStatement stat = _con.prepareStatement(_userSql);
      stat.setObject(1, username);
      ResultSet rs = stat.executeQuery();

      if (rs.next()) {
        int key = rs.getInt(_userTableKey);
        String credentials = rs.getString(_userTablePasswordField);
        stat.close();

        stat = _con.prepareStatement(_roleSql);
        stat.setInt(1, key);
        rs = stat.executeQuery();
        List<String> roles = new ArrayList<String>();
        while (rs.next()) roles.add(rs.getString(_roleTableRoleField));

        stat.close();
        return putUser(
            username,
            Credential.getCredential(credentials),
            roles.toArray(new String[roles.size()]));
      }
    } catch (SQLException e) {
      LOG.warn("UserRealm " + getName() + " could not load user information from database", e);
      closeConnection();
    }
    return null;
  }
  public static final SecurityHandler basicAuth(AuthConfig config) {
    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    securityHandler.setAuthenticator(new BasicAuthenticator());
    securityHandler.setRealmName(config.getRealm());

    ConstraintMapping constraintMapping = new ConstraintMapping();

    Constraint constraint = new Constraint(Constraint.__BASIC_AUTH, USER_ROLE);
    constraint.setAuthenticate(true);

    constraintMapping.setConstraint(constraint);

    constraintMapping.setPathSpec("/*");

    securityHandler.addConstraintMapping(constraintMapping);

    HashLoginService loginService = new HashLoginService();
    loginService.putUser(
        config.getUsername(),
        Credential.getCredential(config.getPassword()),
        new String[] {USER_ROLE});
    loginService.setName(config.getRealm());

    securityHandler.setLoginService(loginService);

    return securityHandler;
  }
  /** Creates a basic auth security handler. */
  private SecurityHandler createSecurityHandler() {
    HashLoginService l = new HashLoginService();
    for (String[] userInfo : TestUsers.USERS) {
      String user = userInfo[0];
      String pwd = userInfo[1];
      String[] roles = new String[] {"apiuser"};
      if (user.startsWith("admin")) roles = new String[] {"apiuser", "apiadmin"};
      l.putUser(user, Credential.getCredential(pwd), roles);
    }
    l.setName("apimanrealm");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("apimanrealm");
    csh.setLoginService(l);

    return csh;
  }
  /**
   * Put user into realm. Called by implementations to put the user data loaded from file/db etc
   * into the user structure.
   *
   * @param userName User name
   * @param info a UserIdentity instance, or a String password or Credential instance
   * @return User instance
   */
  protected synchronized UserIdentity putUser(String userName, Object info) {
    final UserIdentity identity;
    if (info instanceof UserIdentity) identity = (UserIdentity) info;
    else {
      Credential credential =
          (info instanceof Credential)
              ? (Credential) info
              : Credential.getCredential(info.toString());

      Principal userPrincipal = new KnownUser(userName, credential);
      Subject subject = new Subject();
      subject.getPrincipals().add(userPrincipal);
      subject.getPrivateCredentials().add(credential);
      subject.setReadOnly();
      identity = _identityService.newUserIdentity(subject, userPrincipal, IdentityService.NO_ROLES);
    }

    _users.put(userName, identity);
    return identity;
  }
  /**
   * Load info from database
   *
   * @param userName user info to load
   * @exception SQLException
   */
  public UserInfo getUserInfo(String userName) throws Exception {
    Connection connection = null;

    try {
      connection = getConnection();

      // query for credential
      PreparedStatement statement = connection.prepareStatement(userQuery);
      statement.setString(1, userName);
      ResultSet results = statement.executeQuery();
      String dbCredential = null;
      if (results.next()) {
        dbCredential = results.getString(1);
      }
      results.close();
      statement.close();

      // query for role names
      statement = connection.prepareStatement(rolesQuery);
      statement.setString(1, userName);
      results = statement.executeQuery();
      List<String> roles = new ArrayList<String>();

      while (results.next()) {
        String roleName = results.getString(1);
        roles.add(roleName);
      }

      results.close();
      statement.close();

      return dbCredential == null
          ? null
          : new UserInfo(userName, Credential.getCredential(dbCredential), roles);
    } finally {
      if (connection != null) connection.close();
    }
  }
Beispiel #7
0
 public void addUser(String name, String password, String... roles) {
   loginService.putUser(name, Credential.getCredential(password), roles);
 }
  public void runClient(boolean ssl, boolean basicAuth) throws Exception {
    Client client = null;
    if (ssl) {
      TrustManagerFactory trustFactory =
          TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
      trustFactory.init(getKeyStore(CLIENT_TRUSTSTORE_FILE, CLIENT_TRUSTSTORE_PASS));
      TrustManager[] trustManagers = trustFactory.getTrustManagers();

      KeyManagerFactory keyFactory =
          KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      keyFactory.init(
          getKeyStore(CLIENT_KEYSTORE_FILE, CLIENT_KEYSTORE_PASS), CLIENT_KEY_PASS.toCharArray());
      KeyManager[] keyManagers = keyFactory.getKeyManagers();

      HostnameVerifier hostNameVerifier =
          new HostnameVerifier() {

            @Override
            public boolean verify(String hostName, SSLSession session) {
              return true;
            }
          };

      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(keyManagers, trustManagers, new SecureRandom());

      ClientConfig config = new DefaultClientConfig();
      config
          .getProperties()
          .put(
              HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
              new HTTPSProperties(hostNameVerifier, sslContext));

      client = Client.create(config);
    } else {
      client = new Client();
    }

    client.addFilter(new CloseConnectionFilter());

    if (basicAuth) {
      client.addFilter(
          new HTTPBasicAuthFilter(
              USER_NAME, Credential.getCredential(USER_PASS).toString().toString()));
    }

    try {
      LOG.debug(String.format("*****Client***** - Starting"));
      String uri = String.format("%s://localhost:%d/", ssl ? "https" : "http", ssl ? 8443 : 8080);
      WebResource webResource = client.resource(uri);
      LOG.debug(String.format("*****Client***** - Resource: %s", webResource));

      for (int xx = 0; xx < 3; xx++) {
        ClientResponse clientResponse = webResource.get(ClientResponse.class);
        LOG.debug(
            String.format(
                "*****Client***** - Status: %s/%s",
                clientResponse.getStatus(), clientResponse.getStatusInfo()));
        LOG.debug(
            String.format(
                "*****Client***** - Response: %s", clientResponse.getEntity(String.class)));
        LOG.debug(String.format("*****Client***** - Done"));
      }
    } finally {
      client.destroy();
    }
  }