0

I am new to JAX-RS and REST-API.
I am fetching rows from Oracle using REST service. I have placed the connection details in META-INF/context.xml's <Resource> tag where I have encrypted the password variable.
I have a custom Encrypter class where I am encrypting/decrypting the password using a Secret Key that I have hardcoded in my Encrypter class.
My requirement is I want this secret-key to be set in some variable (context variable maybe) so that when user hits the GET method URL like "http://server:8080/myapp/rest/replay/getdata?skey=3456FGR55566DHGGH556gf" I can get the skey parameter from the URL and compare it with the context-variable I have set from my Encryptor class. If both matches then I show the JSON data, else it redirects to a JSP.
Everything is working fine except that I am not able to set this secretKey variable in my Encryptor class.
Here is the flow of code:

public class AuthenticatedEncryptor {

    private static final String ALGORITHM_AES256 = "AES/GCM/NoPadding";
    private final SecretKeySpec secretKeySpec;
    private final Cipher cipher;
    // All other variables...

    //@Context ServletContext context

    AuthenticatedEncryptor() throws AuthenticatedEncryptionException 
    {

        String secretKey = "9B7D2C34A366BF890C730641E6CECF6F";
        //Here I want to set the above variable in Context like:
        //context.setAttriute("skey",secretKey);

        //Code for Constructor
    }

    /*
     * Encrypts plaint text. Returns Encrypted String.
     */
    String encrypt(String plaintext) throws AuthenticatedEncryptionException
    {
        return encrypt(plaintext.getBytes(StandardCharsets.UTF_8));
    }

    String encrypt(byte[] plaintext) throws AuthenticatedEncryptionException
    {
        try 
        {
            byte[] iv = getRandom(IV_LEN);
            Cipher msgcipher = getCipher(Cipher.ENCRYPT_MODE, iv);
            byte[] encryptedTextBytes = msgcipher.doFinal(plaintext);
            byte[] payload = concat(iv, encryptedTextBytes);

            return Base64.getEncoder().encodeToString(payload);
        } 
        catch (BadPaddingException | InvalidKeyException | IllegalBlockSizeException | InvalidAlgorithmParameterException e){
            throw new AuthenticatedEncryptionException(e);
        }
    }

    /*
     * Decrypts plaint text. Returns decrypted String.
     */
    String decrypt(String ciphertext) throws AuthenticatedEncryptionException 
    {
        return decrypt(Base64.getDecoder().decode(ciphertext));
    }

    String decrypt(byte[] cipherBytes) throws AuthenticatedEncryptionException 
    {
        byte[] iv = Arrays.copyOf(cipherBytes, IV_LEN);

        byte[] cipherText = Arrays.copyOfRange(cipherBytes, IV_LEN, cipherBytes.length);
        try {
            Cipher cipher = getCipher(Cipher.DECRYPT_MODE, iv);
            byte[] decrypt = cipher.doFinal(cipherText);
            return new String(decrypt, StandardCharsets.UTF_8);
        } catch (BadPaddingException | InvalidKeyException | IllegalBlockSizeException | InvalidAlgorithmParameterException e) {
            throw new AuthenticatedEncryptionException(e);
        }
    }

    //All other utility methods present here....

}

The above class is used in my custom DataSourceFactory class:

public class EncryptedDataSourceFactory extends DataSourceFactory {

    private AuthenticatedEncryptor encryptor = null;

    public EncryptedDataSourceFactory() {
        try 
        {
            encryptor = new AuthenticatedEncryptor();
        } 
        catch (Exception e) {
            System.out.println("Incorrect Secret-Key specified for Decryption in EncryptedDataSourceFactory.class");
            throw new RuntimeException(e);
        }
    }

    @Override
    public DataSource createDataSource(Properties properties, Context context, boolean XA) throws Exception 
    {
        // Here we decrypt our password.
        PoolConfiguration poolProperties = EncryptedDataSourceFactory.parsePoolProperties(properties);
        poolProperties.setPassword(encryptor.decrypt(poolProperties.getPassword()));

        // The rest of the code is copied from Tomcat's DataSourceFactory.
        if(poolProperties.getDataSourceJNDI() != null && poolProperties.getDataSource() == null) {
            performJNDILookup(context, poolProperties);
        }
        org.apache.tomcat.jdbc.pool.DataSource dataSource = XA ? new XADataSource(poolProperties)
                : new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
        dataSource.createPool();

        return dataSource;
    }

}

The code which I am exposing as GET:

@Path("/replay") 
public class GetData {

    @Context
    private ServletContext context;

    Logger logger = Logger.getLogger(GetData.class.getName());

    @GET 
    @Path("/getdata")
    @Produces(MediaType.APPLICATION_JSON)
    public String getReplayData(@Context HttpHeaders httpHeaders, @Context HttpServletRequest req, @Context HttpServletResponse res)
    {

        /* Loading all HeaderParams */
        List<String> headers = new ArrayList<String>();
        for(String header : httpHeaders.getRequestHeaders().keySet()){
            headers.add(header);
        }
        //...
        //....


        /*Printing all HeaderParams */
        headerValue.forEach((k,v)->logger.info("HEADER: " + k + "-->" + v));


        /* Redirecting Code */
        //I need to access this SKEY attribute I want to set in my Encryptor
        String secretKey = (String)context.getAttribute("skey"); 
        System.out.println("SECRET KEY: "+secretKey);
        boolean redirect = false;
        String redirectVal = headerValue.get("x-test-redirect");
        if(redirectVal!=null && redirectVal.equalsIgnoreCase("Y")){
            redirect = true;
        }
        if(redirect)
        {
            try
            {
                logger.info("Authentication failed for Secret Key. Redirecting to authFailed.jsp...");
                req.getRequestDispatcher("/authFailed.jsp").forward(req, res);
            } catch(Exception e){
                System.out.println("Error in redirecting");
                logger.severe("Error in redirecting");
                logger.log(Level.SEVERE, e.getMessage(), e);
            }
        }

        OracleConn con1 = new OracleConn(env, logPath);
        ResultSet result = con1.exec("select * from mytable");
        System.out.println("Result: "+result.toString());
        logger.info("Result: "+result.toString());


        //parse data to JSON
        JSONArray json = parseJSON(result);
        System.out.println("Result parsed to JSON");
        logger.info("Result parsed to JSON");
        try{
            con1.close();
            return json.toString();

        } catch(Exception e){
            e.printStackTrace();
            logger.log(Level.SEVERE, e.getMessage(), e);
            return "Corrupted JSON";
        }


    }

}

How do I set an variable in my AuthenticatedEncryptor class and get its value in my web-service class GetData ?

aiman
  • 1,049
  • 19
  • 57

1 Answers1

0

I found this amazing solution here:
Share variables between JAX-RS requests

Creating a separate class that implements ServletContextListener:

public class ContextListener implements ServletContextListener
{
    String secretKey = "";
    @Override
    public void contextInitialized(ServletContextEvent sce)
    {
        ServletContext context = sce.getServletContext();
        secretKey = new SaltSecretKey().getSecretKey(); //My custom class
        context.setAttribute("secretKey", secretKey);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) 
    {
        ServletContext context = sce.getServletContext();
        context.removeAttribute("secretKey");
    }

}

..and then specifying this in the web.xml:

<listener>
        <listener-class>my.package.ContextListener</listener-class>
    </listener>
aiman
  • 1,049
  • 19
  • 57