清單 1. 一個典型的策略文件 // Grant these permissions to code loaded from a sample.jar file // in the C drive and if it is signed by XYZ grant codebase "file:/C:/sample.jar", signedby "XYZ" { // Allow socket actions to any host using port 8080 permission java.net.SocketPermission "*:8080", "accept, connect, listen, resolve"; // Allows file access (read, write, execute, delete) in // the user′s home Directory. Permission java.io.FilePermission "${user.home}/-", "read, write, execute, delete"; };
Public void someMethod() { Permission permission = new java.net.SocketPermission("localhost:8080", "connect"); AccessController.checkPermission(permission); // Sensitive code starts here Socket s = new Socket("localhost", 8080); }
許可權 賦予 CodeSource 許可權并不一定意味著答應所暗示的操作。要使操作成功完成,調用棧中的每個類必須有必需的許可權。換句話說,假如您將 java.io.FilePermission 賦給類 B,而類 B 是由類 A 來調用,那么類 A 必須也有相同的許可權或者暗示 java.io.FilePermission 的許可權。
// Example grant entry grant codeBase "file:/C:/sample.jar", signedby "XYZ", principal com.ibm.resource.security.auth.Princip// Allow socket actions to any host using port 8080 permission java.net.SocketPermission "*:8080", "accept, connect, listen, resolve"; // Allows file access (read, write, execute, delete) in // the user′s home directory. Permission java.io.FilePermission "${user.home}/-", "read, write, execute, delete"; };
清單 4. 一個簡單的授權請求 public class JaasExample { public static void main(String[] args) { ... // where authenticatedUser is a Subject with // a PrincipalExample named admin. Subject.doAs(authenticatedUser, new JaasExampleAction()); ... } }
public class JaasExampleAction implements PrivilegedAction { public Object run() { FileWriter fw = new FileWriter("hi.txt"); fw.write("Hello, World!"); fw.close(); } }
為了更結合實際地學習 JAAS,請參閱 Thomas Owusu 的“Enhance Java GSSAPI with a login interface using JAAS”(developerWorks,2001 年 11 月)
“Single Sign On Support in WebSphere Portal Server 1.2”討論了 WebSphere Portal Server 的 JAAS 實現并展示了如何抽取用戶數據并將其提供給一個 portlet 的后端應用程序,或者提供給同一個安全性域中的另一個 WebSphere Application Server。
假如您想深入了解 IBM 在 Java 安全性的發展中所起的歷史性作用,請參閱文章“The evolution of Java security”,在這篇文章中 IBM 工程師討論了 JDK 1.2 安全性模型的優缺點。
您將在 IBM developerWorks Java 技術專區找到數百篇關于 Java 編程各個方面的文章。
關于作者 Carlos Fonseca 目前是 IBM Research 的軟件工程師,他已經做了 10 年的專職軟件開發工作。他開始是從事 C 和 Visual Basic 編程,然后轉向 C++ 編程。在最近六年中,Carlos 致力于面向對象的設計和使用 Java 平臺進行開發,把他的專業技術應用于從 Swing GUI 單機應用程序到使用 J2EE 的服務器端應用程序等項目。當 Carlos 不再從事專業軟件開發時,他還喜歡把編程作為業余愛好。您可以通過 cafonseca@us.ibm.com 與 Carlos 聯系。