Exemple #1
0
  private static AuthConfig.Builder parseDockerConfig(final Path configPath, String serverAddress)
      throws IOException {
    checkNotNull(configPath);
    final AuthConfig.Builder authBuilder = AuthConfig.builder();
    final JsonNode authJson = extractAuthJson(configPath);

    if (isNullOrEmpty(serverAddress)) {
      final Iterator<String> servers = authJson.fieldNames();
      if (servers.hasNext()) {
        serverAddress = servers.next();
      }
    } else {
      if (!authJson.has(serverAddress)) {
        log.error("Could not find auth config for {}. Returning empty builder", serverAddress);
        return AuthConfig.builder().serverAddress(serverAddress);
      }
    }

    final JsonNode serverAuth = authJson.get(serverAddress);
    if (serverAuth != null && serverAuth.has("auth")) {
      authBuilder.serverAddress(serverAddress);
      final String authString = serverAuth.get("auth").asText();
      final String[] authParams = Base64.decodeAsString(authString).split(":");

      if (authParams.length == 2) {
        authBuilder.username(authParams[0].trim());
        authBuilder.password(authParams[1].trim());
      } else {
        log.warn("Failed to parse auth string for {}", serverAddress);
        return authBuilder;
      }
    } else {
      log.warn("Could not find auth field for {}", serverAddress);
      return authBuilder;
    }

    if (serverAuth.has("email")) {
      authBuilder.email(serverAuth.get("email").asText());
    }

    return authBuilder;
  }
  @Override
  public void filter(ContainerRequestContext requestContext) throws IOException {
    List<String> authHeader = requestContext.getHeaders().get(AUTHORIZATION_KEY_NAME);
    if (requestContext.getUriInfo().getAbsolutePath().getPath().contains(SECURED_URL)
        && authHeader != null
        && authHeader.size() > 0) {
      String authToken = authHeader.get(0);
      authToken = authToken.replace(AUTHORIZATION_BASIC_PREFIX, "");
      String authTokenDecoded = Base64.decodeAsString(authToken.getBytes("UTF-8"));
      StringTokenizer tokenizer = new StringTokenizer(authTokenDecoded, ":");
      String userName = tokenizer.nextToken();
      String password = tokenizer.nextToken();
      if (userName.equalsIgnoreCase("user") && password.equalsIgnoreCase("password")) return;
    }

    Response unauthorizedStatus =
        Response.status(Response.Status.UNAUTHORIZED)
            .entity("User cannot Access the resource")
            .build();
    requestContext.abortWith(unauthorizedStatus);
  }
 /**
  * Build Authorization header for final user.
  *
  * @param username target username
  * @param password target password
  * @return target header
  */
 public static String buildAuthorization4UserName(String username, String password) {
   return " Basic " + new String(Base64.encodeAsString(username + ":" + password));
 }
Exemple #4
0
  /**
   * The response entity from message service is
   * {"statusCode":"000000","templateSMS":{"dateCreated":"20140827105250",
   * "smsMessageSid":"20140827105250065847"}}
   *
   * @param phoneNumber
   * @return
   * @throws NoSuchAlgorithmException
   * @throws UnsupportedEncodingException
   */
  @GET
  @Path("registration/sms")
  @Produces(MediaType.APPLICATION_JSON)
  public Response sendVerifyMessageToMobile(@QueryParam("phoneNumber") String phoneNumber)
      throws NoSuchAlgorithmException, UnsupportedEncodingException {
    if (phoneNumber == null) {
      return Response.ok(
              new PhoneVerifyResponse(
                  AuthenticationConstants.MESSAGESENDFAILURE,
                  "Parameter phoneNumber provided is null",
                  null))
          .build();
    }
    Properties tzProperties = PropertiesUtils.getProperties(servletConfig.getServletContext());
    SslConfigurator sslConfig =
        SslConfigurator.newInstance()
            .trustStoreFile(tzProperties.getProperty("ssl.trust.store.file"))
            .trustStorePassword(tzProperties.getProperty("ssl.trust.store.pass"))
            .trustStoreType("JKS")
            .trustManagerFactoryAlgorithm("PKIX")
            .keyStoreFile(tzProperties.getProperty("ssl.key.store.file"))
            .keyPassword(tzProperties.getProperty("ssl.key.store.pass"))
            .keyStoreType("JKS")
            .keyManagerFactoryAlgorithm("SunX509")
            .keyStoreProvider("SUN")
            .securityProtocol("SSL");

    SSLContext sslContext = sslConfig.createSSLContext();
    Client client = ClientBuilder.newBuilder().sslContext(sslContext).build();

    WebTarget target = client.target(tzProperties.getProperty("mobile.verify.service"));
    String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    String accountSid = tzProperties.getProperty("mobile.account.sid");
    String encodeString = accountSid + tzProperties.getProperty("mobile.auth.token") + timeStamp;
    String authenticationString = accountSid + ":" + timeStamp;
    String sig = new EncryptUtil().md5Digest(encodeString);

    JsonObjectBuilder messageBuilder = Json.createObjectBuilder();
    JsonArrayBuilder datasBuilder = Json.createArrayBuilder();
    String verificationCode = String.valueOf(VerificationCodeGenerator.randInt(100000, 999999));
    datasBuilder.add(verificationCode).add(tzProperties.getProperty("mobile.code.active.time"));
    messageBuilder
        .add("to", phoneNumber)
        .add("appId", tzProperties.getProperty("mobile.appid"))
        .add("templateId", tzProperties.getProperty("mobile.templateid"))
        .add("datas", datasBuilder);

    Response providerResponse =
        target
            .queryParam("sig", sig)
            .request(MediaType.APPLICATION_JSON)
            .header(HttpHeaders.AUTHORIZATION, Base64.encodeAsString(authenticationString))
            .post(Entity.entity(messageBuilder.build(), MediaType.APPLICATION_JSON));
    JsonObject jsonObject = providerResponse.readEntity(JsonObject.class);
    if (jsonObject.getString("statusCode").equals("000000")) {
      TokenHolder.verificationCodeMap.put(phoneNumber, verificationCode);
      return Response.ok(
              new PhoneVerifyResponse(
                  AuthenticationConstants.MESSAGESENDSUCCESS,
                  jsonObject.toString(),
                  verificationCode))
          .build();
    } else {
      return Response.ok(
              new PhoneVerifyResponse(
                  AuthenticationConstants.MESSAGESENDFAILURE, jsonObject.toString(), null))
          .build();
    }
  }