本文介紹了限制執行第三方軟件的線程的權限的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在開發一個基于Eclipse的應用程序,該應用程序能夠執行第三方組件(不是Eclipse插件)。
每個組件都有一個自定義描述符,該描述符列出了權限(具有相應的動機)。這樣,最終用戶可以決定是否執行它。
組件在單獨的線程中執行。如何根據描述符限制這些線程的權限,而不限制整個應用程序?
推薦答案
首先,您應該打開安全管理器。然后創建具有所需權限的AccessControlContext。(在我的示例中沒有權限。)最后執行AccessController.doPrivileged(…)方法中的第三方代碼。
這是一個非常簡單的解決方案:
public abstract class SafeRunnable implements Runnable {
public abstract void protectedRun();
@Override
public final void run() {
CodeSource nullSource = new CodeSource(null, (CodeSigner[]) null);
PermissionCollection noPerms = new Permissions();
ProtectionDomain domain = new ProtectionDomain(nullSource, noPerms);
AccessControlContext safeContext = new AccessControlContext(
new ProtectionDomain[] { domain });
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
protectedRun();
return null;
}
}, safeContext);
}
}
測試SafeRunnable:
public static void main(String args[]) throws Exception {
// Turn on the security management
SecurityManager sm = new SecurityManager();
System.setSecurityManager(sm);
new Thread(new SafeRunnable() {
public void protectedRun() {
// friendly operation:
System.out.println("Hello");
}
}).start();
new Thread(new SafeRunnable() {
public void protectedRun() {
// malicious operation
System.exit(0);
}
}).start();
}
第一線程打印Hello,第二線程拋出AccessControlException: access denied ("java.lang.RuntimePermission" "exitVM.0")
這篇關于限制執行第三方軟件的線程的權限的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,