[英]How to set context variable in JAX-RS REST-API?
我是JAX-RS和REST-API的新手。
我正在使用REST服務從Oracle獲取行。 我已將連接詳細信息放在META-INF/context.xml
的<Resource>
標記中,在此標記中已加密了password
變量。
我有一個自定義的Encrypter類,在這里我使用我在Encrypter類中硬編碼的密鑰對密碼進行加密/解密。
我的要求是,我希望將此密鑰設置在某個變量(可能是上下文變量)中,以便當用戶點擊GET方法URL時,例如"http://server:8080/myapp/rest/replay/getdata?skey=3456FGR55566DHGGH556gf"
我可以從URL獲取skey
參數,並將其與我在Encryptor類中設置的上下文變量進行比較。 如果兩個都匹配,那么我將顯示JSON數據,否則它將重定向到JSP。
除了無法在我的Encryptor類中設置此secretKey變量之外,其他所有程序都工作正常。
這是代碼流:
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....
}
上面的類在我的自定義DataSourceFactory類中使用:
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;
}
}
我作為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";
}
}
}
如何在AuthenticatedEncryptor
類中設置變量,並在Web服務類GetData
獲取其值?
我在這里找到了這個驚人的解決方案:
在JAX-RS請求之間共享變量
創建一個單獨的類來實現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");
}
}
..,然后在web.xml中指定:
<listener>
<listener-class>my.package.ContextListener</listener-class>
</listener>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.