- 浏览: 228058 次
- 性别:
- 来自: 北京
文章分类
- 全部博客 (209)
- database (25)
- java技巧 (25)
- TC总结 (4)
- J2EE (8)
- 算法 (6)
- blog (4)
- php (4)
- linux & mac (19)
- 其它技术 (4)
- javascript&ajax (26)
- 测试技术 (8)
- XML&HTML (2)
- ORM (hibernate ...) (11)
- eclipse (5)
- 技术书籍 (8)
- 项目管理,cmmi (3)
- 硬件技术 (1)
- REST, web service, web架构 (1)
- 卓有成效程序员 (2)
- qone开发 (1)
- Design (4)
- .net (5)
- SCM (4)
- css (23)
- programming languages (1)
- ide (2)
- CSS Patterns (18)
- security (1)
- android (5)
最新评论
-
Virtoway:
说到Angular JS刚读到一片美国构架师的文章关于使用An ...
angular js: angular.bind example -
08284008:
该毛线啊,一点解释的都没有,怎么看
Thread join() 用法 -
Rex86lxw:
在eclipse中我一直用Navigator查看编写代码的,可 ...
eclipse不能自动编译,不报错 -
mistake:
..............
Angular js scope: the child scope would inherit from the parent scope -
sparrow1314:
very good! thanks!
IE下JS调试工具
http://publib.boulder.ibm.com/infocenter/iseries/v6r1m0/index.jsp?topic=/rzaha/api.htm
Java Authentication and Authorization Service (JAAS) 1.0
The Java™ Authentication and Authorization Service (JAAS) is a standard extension to the Java 2 Software Development Kit, version 1.3. Currently, Java 2 provides codesource-based access controls (access controls based on where the code originated from and who signed the code). It lacks, however, the ability to additionally enforce access controls based on who runs the code. JAAS provides a framework that augments the Java 2 security model with such support.
Developer's Guide
References
Overview
The Java Authentication and Authorization Service (JAAS) is a standard extension to the Java 2 Software Development Kit, version 1.3. Currently, Java 2 provides codesource-based access controls (access controls based on where the code originated from and who signed the code). It lacks, however, the ability to additionally enforce access controls based on who runs the code. JAAS provides a framework that augments the Java 2 security model with such support.
This document was last updated March 17, 2000.
Who Should Read This Document
This document is intended for experienced programmers wanting to create applications constrained by a codesource-based and Subject-based security model.
Related Documentation
This document assumes you have already read the following documentation:
- Java 2 Software Development Kit API Specification
- JAAS API Specification
- Security and the Java platform
A supplement to this guide is the LoginModule Developer's Guide that is supplied by Sun Microsystems, Inc.
Introduction
The JAAS infrastructure can be divided into two main components: an authentication component and an authorization component. The JAAS authentication component provides the ability to reliably and securely determine who is currently processing Java code, regardless of whether the code is running as an application, an applet, a bean, or a servlet. The JAAS authorization component supplements the existing Java 2 security framework by providing the means to restrict the processing Java code from performing sensitive tasks, depending on its codesource (as is done in Java 2) and depending on who was authenticated.
JAAS authentication is performed in a pluggable fashion. This permits Java applications to remain independent from underlying authentication technologies. Therefore new or updated authentication technologies can be plugged under an application without requiring modifications to the application itself. Applications enable the authentication process by instantiating a
LoginContextobject, which in turn references a
Configurationto determine the authentication technology, or
LoginModule, to be used in performing the authentication. Typical LoginModules may prompt for and verify a username and password. Others may read and verify a voice or fingerprint sample.
Once the user processing the code has been authenticated, the JAAS authorization component works in conjunction with the existing Java 2 access control model to protect access to sensitive resources. Unlike in Java 2, where access control decisions are based solely on code location and code signers (a
CodeSource), in JAAS access control decisions are based both on the processing code's
CodeSource, as well as on the user running the code, or the
Subject. Note that the JAAS policy merely extends the Java 2 policy with the relevant Subject-based information. Therefore permissions recognized and understood in Java 2 (
java.io.FilePermissionand
java.net.SocketPermission, for example) are also understood and recognized by JAAS. Furthermore, although the JAAS security policy is physically separate from the existing Java 2 security policy, the two policies, together, form one logical policy.
Core Classes
The JAAS core classes can be broken into 3 categories: Common, Authentication, and Authorization.- Common Classes
- Subject, Principals, Credentials
- Authentication Classes
- LoginContext, LoginModule, CallbackHandler, Callback
- Authorization Classes
- Policy, AuthPermission, PrivateCredentialPermission
Common Classes
Common classes are shared within both the JAAS authentication and authorization components.The key JAAS class is
Subject, which represents a grouping of related information for a single entity such as a person. It encompasses the entity's Principals, public credentials, and private credentials.
Note that JAAS uses the existing Java 2
java.security.Principalinterface to represent a Principal. Also note that JAAS does not introduce a separate credential interface or class. A credential, as defined by JAAS, may be any Object.
Subject
To authorize access to resources, applications first need to authenticate the source of the request. The JAAS framework defines the term, Subject, to represent the source of a request. A Subject may be any entity, such as a person or service. Once authenticated, a Subject is populated with associated identities, or Principals. A Subject may have many Principals. For example, a person may have a name Principal ("John Doe") and a SSN Principal ("123-45-6789") which distinguishes it from other Subjects.A
Subjectmay also own security-related attributes, which are referred to as credentials. Sensitive credentials that require special protection, such as private cryptographic keys, are stored within a private credential
Set. Credentials intended to be shared, such as public key certificates or Kerberos tickets are stored within a public credential
Set. Different permissions are required to access and modify the different credential Sets.
Subjects are created using these constructors:
public Subject(); public Subject(boolean readOnly, Set principals, Set pubCredentials, Set privCredentials);The first constructor creates a Subject with empty (non-null) Sets of Principals and credentials. The second constructor creates a Subject with the specified Sets of Principals and credentials. It also has a boolean argument which can create a read-only Subject (immutable Principal and credential Sets).
An alternative way to obtain a reference to an authenticated Subject without using these constructors will be shown in the LoginContext section.
If a Subject was not instantiated to be in a read-only state, it can be set to a read-only state by calling this method:
public void setReadOnly();An
AuthPermission("setReadOnly")is required to invoke this method. Once in a read-only state, any attempt to add or remove Principals or credentials will result in an
IllegalStateExceptionbeing thrown.
This method may be called to test a Subject's read-only state:
public boolean isReadOnly();To retrieve the Principals associated with a Subject, two methods are available:
public Set getPrincipals(); public Set getPrincipals(Class c);The first method returns all Principals contained in the Subject, while the second method only returns those Principals that are an instance of the specified Class c, or an instance of a subclass of Class c. An empty set will be returned if the Subject does not have any associated Principals.
To retrieve the public credentials associated with a Subject, these methods are available:
public Set getPublicCredentials(); public Set getPublicCredentials(Class c);The observed behavior of these methods is identical to that for the
getPrincipalsmethod.
To access private credentials associated with a Subject, the following methods are available:
public Set getPrivateCredentials(); public Set getPrivateCredentials(Class c);The observed behavior of these methods is identical to that for the
getPrincipalsand
getPublicCredentialsmethods.
To modify or operate upon a Subject's Principal Set, public credential Set, or private credential Set, callers use the methods defined in the
java.util.Setclass. The following example demonstrates this:
Subject subject; Principal principal; Object credential; // add a Principal and credential to the Subject subject.getPrincipals().add(principal); subject.getPublicCredentials().add(credential);Note that an
AuthPermission("modifyPrincipals"),
AuthPermission("modifyPublicCredentials"), or
AuthPermission("modifyPrivateCredentials")is required to modify the respective Sets. Also note that only the sets returned via the
getPrincipals,
getPublicCredentials, and
getPrivateCredentialsmethods are backed by the Subject's respective internal sets. Therefore any modification to the returned set affects the internal sets as well. The sets returned via the
getPrincipals(Class c),
getPublicCredentials(Class c), and
getPrivateCredentials(Class c)methods are not backed by the Subject's respective internal sets. A new set is created and returned for each method invocation. Modifications to these sets will not affect the Subject's internal sets. The following method returns the Subject associated with the specified
AccessControlContext, or null if no Subject is associated with the specified
AccessControlContext.
public static Subject getSubject(final AccessControlContext acc);An
AuthPermission("getSubject")is required to call
Subject.getSubject.
The Subject class also includes these methods inherited from
java.lang.Object:
public boolean equals(Object o); public String toString(); public int hashCode();
<!-- --> The following static methods may be called to perform work as a particular Subject:
public static Object doAs(final Subject subject, final java.security.PrivilegedAction action); public static Object doAs(final Subject subject, final java.security.PrivilegedExceptionAction action) throws java.security.PrivilegedActionException;Both methods first associate the specified subject with the current Thread's
AccessControlContext, and then process the action . This achieves the effect of having the action run as the subject . The first method can throw runtime exceptions but normal processing has it returning an Object from the run() method of its action argument. The second method behaves similarly except that it can throw a checked exception from its
PrivilegedExceptionActionrun() method. An
AuthPermission("doAs")is required to call the
doAsmethods.
Here are two examples utilizing the first
doAsmethod. Assume that a
Subjectwith a Principal of class
com.ibm.security.Principalnamed "BOB" has been authenticated by a
LoginContext"lc". Also, assume that a SecurityManager has been installed, and the following exists in the JAAS access control policy (see the Policy section for more details on the JAAS policy file):
// Grant "BOB" permission to read the file "foo.txt" grant Principal com.ibm.security.Principal "BOB" { permission java.io.FilePermission "foo.txt", "read"; };
Subject.doAs Example 1
class ExampleAction implements java.security.PrivilegedAction { public Object run() { java.io.File f = new java.io.File("foo.txt"); // exists() invokes a security check if (f.exists()) { System.out.println("File foo.txt exists."); } return null; } } public class Example1 { public static void main(String[] args) { // Authenticate the subject, "BOB". // This process is described in the // LoginContext section . Subject bob; ... // perform "ExampleAction" as "BOB": Subject.doAs(bob, new ExampleAction()); } }During processing,
ExampleActionwill encounter a security check when it makes a call to,
f.exists(). However, since
ExampleActionis running as "BOB", and because the JAAS policy (above) grants the necessary
FilePermissionto "BOB", the
ExampleActionwill pass the security check.
Example 2 has the same scenario as Example 1.
Subject.doAs Example 2
public class Example2 { // Example of using an anonymous action class. public static void main(String[] args) { // Authenticate the subject, "BOB". // This process is described in the // LoginContext section . Subject bob; ... // perform "ExampleAction" as "BOB": Subject.doAs(bob, new ExampleAction() { public Object run() { java.io.File f = new java.io.File("foo.txt"); if (f.exists()) { System.out.println("File foo.txt exists."); } return null; } }); } }Both examples throw a
SecurityExceptionif the example permission grant statement is altered incorrectly, such as adding an incorrect CodeBase or changing the Principal to "MOE". Removing the Principal field from the grant block and then moving it to a Java 2 policy file will not cause a
SecurityExceptionto be thrown because the permission is more general now (available to all Principals).
Since both examples perform the same function, there must be a reason to write code one way over the other. Example 1 may be easier to read for some programmers unfamiliar with anonymous classes. Also, the action class could be placed in a separate file with a unique CodeBase and then the permission grant could utilize this information. Example 2 is more compact and the action to be performed is easier to find since it is right there in the
doAscall.
<!-- --> The following methods also perform work as a particular Subject. However, the
doAsPrivilegedmethods will have security checks based on the supplied action and subject . The supplied context will be tied to the specified subject and action . A null context object will disregard the current
AccessControlContextaltogether.
public static Object doAsPrivileged(final Subject subject, final java.security.PrivilegedAction action, final java.security.AccessControlContext acc); public static Object doAsPrivileged(final Subject subject, final java.security.PrivilegedExceptionAction action, final java.security.AccessControlContext acc) throws java.security.PrivilegedActionException;The
doAsPrivilegedmethods behave similarly to the
doAsmethods: the subject is associated with the context acc , an action is performed, and runtime exceptions or checked exceptions may be thrown. However, the
doAsPrivilegedmethods first empties the existing Thread's
AccessControlContextbefore associating the subject with the supplied context, and before invoking the action . A null acc argument has the effect of causing access control decisions (invoked while the action processes) to be based solely upon the subject and action . An
AuthPermission("doAsPrivileged")is required when calling the
doAsPrivilegedmethods.
Principals
As mentioned previously, Principals may be associated with a Subject. Principals represent Subject identities, and must implement thejava.security.Principaland
java.io.Serializableinterfaces. The Subject section describes ways to update the Principals associated with a Subject.
Credentials
Public and private credential classes are not part of the core JAAS class library. Any java class, therefore, can represent a credential. However, developers may elect to have their credential classes implement two interfaces related to credentials: Refreshable and Destroyable.Refreshable
This interface provides the capability for a credential to refresh itself. For example, a credential with a particular time-restricted lifespan may implement this interface to allow callers to refresh the time period for which it is valid. The interface has two abstract methods:boolean isCurrent();Determines if the credential is current or valid.
void refresh() throws RefreshFailedException;Updates or extends the validity of the credential. This method implementation performs an
AuthPermission("refreshCredential")security check to ensure the caller has permission to refresh the credential.
Destroyable
This interface provides the capability of destroying the contents within a credential. The interface has two abstract methods:boolean isDestroyed();Determines if the credential has been destroyed.
void destroy() throws DestroyFailedException;Destroys and clears the information associated with this credential. Subsequent calls to certain methods on this credential will result in an
IllegalStateExceptionbeing thrown. This method implementation performs an
AuthPermission("destroyCredential")security check to ensure the caller has permission to destroy the credential.
Authentication Classes
To authenticate aSubject, the following steps are performed:
- An application instantiates a
LoginContext
. - The
LoginContext
consults a configuration to load all of the LoginModules configured for that application. - The application invokes the LoginContext's login method.
- The login
method invokes all of the loaded LoginModules. Each
LoginModule
attempts to authenticate theSubject
. Upon success, LoginModules associate relevant Principals and credentials with theSubject
. - The
LoginContext
returns the authentication status to the application. - If authentication succeeded, the application retrieves the authenticated
Subject
from theLoginContext
.
LoginContext
TheLoginContextclass provides the basic methods used to authenticate Subjects, and provides a way to develop an application independent of the underlying authentication technology. The
LoginContextconsults a configuration
Configurationto determine the authentication services, or LoginModules, configured for a particular application. Therefore, different LoginModules can be plugged in under an application without requiring any modifications to the application itself.
LoginContextoffers four constructors to choose from:
public LoginContext(String name) throws LoginException; public LoginContext(String name, Subject subject) throws LoginException; public LoginContext(String name, CallbackHandler callbackHandler) throws LoginException public LoginContext(String name, Subject subject, CallbackHandler callbackHandler) throws LoginExceptionAll of the constructors share a common parameter: name . This argument is used by the
LoginContextto index the login Configuration. Constructors that do not take a
Subjectas an input parameter instantiate a new
Subject. Null inputs are disallowed for all constructors. Callers require an
AuthPermission("createLoginContext")to instantiate a
LoginContext.
Actual authentication occurs with a call to the following method:
public void login() throws LoginException;When login is invoked, all of the configured LoginModules' respective login methods are invoked to perform the authentication. If the authentication succeeded, the authenticated
Subject(which may now hold Principals, public credentials, and private credentials) can be retrieved by using the following method:
public Subject getSubject();To logout a
Subjectand remove its authenticated Principals and credentials, the following method is provided:
public void logout() throws LoginException;
The following snippet of code in an application will authenticate a Subject called "bob" after accessing a configuration file with a configuration entry named "moduleFoo":
Subject bob = new Subject(); LoginContext lc = new LoginContext("moduleFoo", bob); try { lc.login(); System.out.println("authentication successful"); } catch (LoginException le) { System.out.println("authentication unsuccessful"+le.printStackTrace()); }This snippet of code in an application will authenticate a "nameless" Subject and then use the getSubject method to retrieve it:
LoginContext lc = new LoginContext("moduleFoo"); try { lc.login(); System.out.println("authentication successful"); } catch (LoginException le) { System.out.println("authentication unsuccessful"+le.printStackTrace()); } Subject subject = lc.getSubject();If the authentication failed, then getSubject returns null. Also, there isn't an
AuthPermission("getSubject")required to do this as is the case for
Subject.getSubject
LoginModule
The LoginModule interface gives developers the ability to implement different kinds of authentication technologies that can be plugged under an application. For example, one type of
LoginModulemay perform a username/password-based form of authentication.
The LoginModule Developer's Guide is a detailed document that gives developers step-by-step instructions for implementing LoginModules.
To instantiate a
LoginModule, a
LoginContextexpects each
LoginModuleto provide a public constructor that takes no arguments. Then, to initialize a
LoginModulewith the relevant information, a
LoginContextcalls the LoginModule's
initializemethod. The provided subject is guaranteed to be non-null.
void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options);This following method begins the authentication process:
boolean login() throws LoginException;An example method implementation may prompt the user for a username and password, and then verify the information against the data stored in a naming service such as NIS or LDAP. Alternative implementations might interface smart cards and biometric devices, or may simply extract user information from the underlying operating system. This is considered phase 1 of the JAAS authentication process.
The following method completes and finalizes the authentication process:
boolean commit() throws LoginException;If phase 1 of the authentication process was successful, then this method continues with phase 2 : associating Principals, public credentials, and private credentials with the Subject. If phase 1 failed, then the commit method removes any previously stored authentication state, such as usernames and passwords.
The following method halts the authentication process if phase 1 was unsuccessful:
boolean abort() throws LoginException;Typical implementations of this method clean up previously stored authentication state, such as usernames or passwords. The following method logs out a Subject:
boolean logout() throws LoginException;This method removes the Principals and credentials originally associated with the
Subjectduring the
commitoperation. Credentials are destroyed upon removal.
CallbackHandler
In some cases a LoginModule must communicate with the user to obtain authentication information. LoginModules use a CallbackHandler for this purpose. Applications implement the CallbackHandler interface and pass it to the LoginContext, which forwards it directly to the underlying LoginModules. LoginModules use the CallbackHandler both to gather input from users (such as a password or smart card pin number) or to supply information to users (such as status information). By allowing the application to specify the CallbackHandler, underlying LoginModules can remain independent of the different ways applications interact with users. For example, the implementation of a CallbackHandler for a GUI application might display a Window to solicit input from a user. The implementation of a CallbackHandler for a non-GUI tool might prompt the user for input directly from the command line.
CallbackHandleris an interface with one method to implement:
void handle(Callback[] callbacks) throws java.io.IOException, UnsupportedCallbackException;
Callback
The javax.security.auth.callback package contains the Callback interface as well as several implementations. LoginModules may pass an array of Callbacks directly to the handle method of a CallbackHandler.Consult the various Callback APIs for more information on their use.
Authorization Classes
Upon successful authentication of aSubject, fine-grained access controls can be placed upon that
Subjectby invoking the Subject.doAs or Subject.doAsPrivileged methods. The permissions granted to that
Subjectare configured in a JAAS
Policy.
Policy
This is an abstract class for representing the system-wide JAAS access control. As a default, JAAS provides a file-based subclass implementation, PolicyFile. EachPolicysubclass must implement the following methods:
public abstract java.security.PermissionCollection getPermissions (Subject subject, java.security.CodeSource cs); public abstract void refresh();The
getPermissionsmethod returns the permissions granted to the specified
Subjectand
CodeSource. The
refreshmethod updates the runtime
Policywith any modifications made since the last time it was loaded from its permanent store (a file or database, for example). The
refreshmethod requires an
AuthPermission("refreshPolicy").
The following method retrieves the current runtime
Policyobject, and is protected with a security check that requires the caller to have an
AuthPermission("getPolicy").
public static Policy getPolicy();The following example code demonstrates how a
Policyobject can be queried for the set of permissions granted to the specified
Subjectand
CodeSource:
policy = Policy.getPolicy(); PermissionCollection perms = policy.getPermissions(subject, codeSource);To set a new
Policyobject for the Java runtime, the
Policy.setPolicymethod may be used. This method requires the caller to have an
AuthPermission("setPolicy").
public static void setPolicy(Policy policy);
Policy File Sample Entries:
These examples are relevant only for the default PolicyFile implementation.
Each entry in the
Policyis represented as a grant entry. Each grant entry specifies a codebase/code-signers/Principals triplet, as well as the Permissions granted to that triplet. Specifically, the permissions will be granted to any code downloaded from the specified codebase and signed by the specified code signers , so long as the
Subjectrunning that code has all of the specified Principals in its
Principalset. Refer to the Subject.doAs examples to see how a
Subjectbecomes associated with running code.
grant CodeBase ["URL"], Signedby ["signers"], Principal [Principal_Class] "Principal_Name", Principal ... { permission Permission_Class ["Target_Name"] [, "Permission_Actions"] [, signedBy "SignerName"]; }; // example grant entry grant CodeBase "http://griffin.ibm.com", Signedby "davis", Principal com.ibm.security.auth.NTUserPrincipal "kent" { permission java.io.FilePermission "c:/kent/files/*", "read, write"; };If no Principal information is specified in the JAAS
Policygrant entry, a parsing exception will be thrown. However, grant entries that already exist in the regular Java 2 codesource-based policy file (and therefore have no Principal information) are still valid. In those cases, the Principal information is implied to be '*' (the grant entries applies to all Principals).
The CodeBase and Signedby components of the grant entry are optional in the JAAS
Policy. If they are not present, then any codebase will match, and any signer (including unsigned code) will match.
In the example above, the grant entry specifies that code downloaded from "http://griffin.ibm.com", signed by "davis", and running as the NT user "kent", has one
Permission. This
Permissionpermits the processing code to read and write files in the directory "c:\kent\files".
Multiple Principals may be listed within one grant entry. The current
Subjectrunning the code must have all of the specified Principals in its
Principalset to be granted the entry's Permissions.
grant Principal com.ibm.security.auth.NTUserPrincipal "kent", Principal com.ibm.security.auth.NTSidGroupPrincipal "S-1-1-0" { permission java.io.FilePermission "c:/user/kent/", "read, write"; permission java.net.SocketPermission "griffin.ibm.com", "connect"; };This entry grants any code running as both the NT user "kent" with the NT group identification number "S-1-1-0", permission to read and write files in "c:\user\kent", as well as permission to make socket connections to "griffin.ibm.com".
AuthPermission
This class encapsulates the basic permissions required for JAAS. An AuthPermission contains a name (also referred to as a "target name") but no actions list; you either have the named permission or you don't. In addition to inherited methods (from thePermissionclass), an
AuthPermissionhas two public constructors:
public AuthPermission(String name); public AuthPermission(String name, String actions);The first constructor creates a new AuthPermission with the specified name. The second constructor also creates a new AuthPermission object with the specified name, but has an additional actions argument which is currently unused and are null. This constructor exists solely for the
Policyobject to instantiate new Permission objects. For most code, the first constructor is appropriate.
The AuthPermission object is used to guard access to the Policy, Subject, LoginContext, and Configuration objects. Refer to the AuthPermission Javadoc for the list of valid names that are supported.
PrivateCredentialPermission
This class protects access to a Subject's private credentials and provides one public constructor:public PrivateCredentialPermission(String name, String actions);Refer to the PrivateCredentialPermission Javadoc for more detailed information on this class.
Implementation
Note: Appendix A contains a sample java.security file that includes the static properties mentioned here.Because there exists default values for JAAS providers and policy files, users need not statically (in the java.security file) nor dynamically (command line -D option) list their values in order to implement JAAS. Also, the default configuration and policy file providers may be replaced by a user-developed provider. Therefore this section is an attempt to explain the JAAS default providers and policy files as well as the properties that enable alternative providers.
Read the Default Policy File API and Default Configuration File API for more information than is summarized here.
Authentication Provider
The authentication provider, or configuration class, is statically set with
login.configuration.provider=[class]in the java.security file. This provider creates the
Configurationobject.
For example:
login.configuration.provider=com.foo.ConfigIf the Security property
login.configuration.provideris not found in java.security, then JAAS will set it to the default value:
com.ibm.security.auth.login.ConfigFile.
If a security manager is set before the
Configurationis created, then an
AuthPermission("getLoginConfiguration")will be required to be granted.
There isn't a way to dynamically set the configuration provider on the command line.
Authentication Configuration File
The authentication configuration files may be statically set in java.security with
login.config.url.n =[URL], where n is a consecutively number integer starting with 1. The format is identical to the format for Java security policy files (policy.url.n=[URL]).
If the Security property
policy.allowSystemPropertyis set to "true" in java.security, then users can dynamically set policy files on the command line utilizing the -D option with this property:
java.security.auth.login.config. The value may be a path or URL. For example (on NT):
... -Djava.security.auth.login.config=c:\config_policy\login.config ... or ... -Djava.security.auth.login.config=file:c:/config_policy/login.config ...Note: using double equal signs (==) on the command line allows a user to override all other policy files found.
If no configuration files can be found statically or dynamically, JAAS will try to load the configuration file from this default location:
${user.home} \.java.login.configwhere ${user.home} is a system dependent location.
<!-- --> Authorization Provider
The authorization provider, or JAAS Policy class, is statically set with
auth.policy.provider=[class]in the java.security file. This provider creates the JAAS Subject-based
Policyobject.
For example:
auth.policy.provider=com.foo.PolicyIf the Security property
auth.policy.provideris not found in java.security, then JAAS will set it to the default value:
com.ibm.security.auth.PolicyFile.
If a security manager is set before the
Configurationis created, then an
AuthPermission("getPolicy")will be required to be granted.
There isn't a way to dynamically set the authorization provider on the command line.
Authorization Policy File
The authorization policy files may be statically set in java.security with
auth.policy.url.n =[URL], where n is a consecutively number integer starting with 1. The format is identical to the format for Java security policy files (policy.url.n=[URL]).
If the Security property
policy.allowSystemPropertyis set to "true" in java.security, then users can dynamically set policy files on the command line utilizing the -D option with this property:
java.security.auth.policy. The value may be a path or URL. For example (on NT):
... -Djava.security.auth.policy=c:\auth_policy\java.auth.policy ... or ... -Djava.security.auth.policy=file:c:/auth_policy/java.auth.policy ...Note: using double equal signs (==) on the command line allows a user to override all other policy files found.
There is not a default location to load an authorization policy from.
"Hello World", JAAS style!
Put on your dark sunglasses and favorite fedora hat, then grab an alto sax ... it's time to get JAAS -y! Yes, another "Hello World!" program. In this section, a program will be made available to test your JAAS installation.
Installation It is assumed that JAAS has been installed. For example, the JAAS JAR files have been copied to your Development Kit's extensions directory.
Retrieve Files Download theHelloWorld.tar to your test directory. Expand it using "jar xvf HelloWorld.tar".
Verify the contents of your test directory.
source files :- HWLoginModule.java
- HWPrincipal.java
- HelloWorld.java
- The source files have been precompiled for you into the classes directory.
- jaas.config
- java2.policy
- jaas.policy
Compile Source Files The three source files, HWLoginModule.java , HWPrincipal.java and HelloWorld.java , are already compiled and therefore do not need to be compiled.
If any of the source files are modified, then change to the test directory that they were saved to and enter:
javac -d .\classes *.javaThe classpath needs the classes directory (.\classes) added to it in order to compile the classes.
Note:
HWLoginModuleand
HWPrincipalare in the
com.ibm.securitypackage and will be created in the appropriate directory during compilation (>test_dir<\classes\com\ibm\security).
Examine Policy Files The configuration file, jaas.config , contains one entry:
helloWorld { com.ibm.security.HWLoginModule required debug=true; };Only one
LoginModuleis supplied with the test case. When processing the HelloWorld application, experiment by changing the
LoginModuleControlFlag(required, requisite, sufficient, optional) and deleting the debug flag. If more LoginModules are available for testing, then feel free to alter this configuration and experiment with multiple LoginModules.
HWLoginModulewill be discussed shortly.
The Java 2 policy file, java2.policy , contains one permission block:
grant { permission javax.security.auth.AuthPermission "createLoginContext"; permission javax.security.auth.AuthPermission "modifyPrincipals"; permission javax.security.auth.AuthPermission "doAsPrivileged"; };The three permissions are required because the HelloWorld application (1) creates a LoginContext object, (2) modifies the Principals of the the authenticated
Subjectand (3) calls the doAsPrivileged method of the
Subjectclass.
The JAAS policy file, jaas.policy , also contains one permission block:
grant Principal com.ibm.security.HWPrincipal "bob" { permission java.util.PropertyPermission "java.home", "read"; permission java.util.PropertyPermission "user.home", "read"; permission java.io.FilePermission "foo.txt", "read"; };The three permissions are initially granted to an
HWPrincipalnamed bob . The actual Principal added to the authenticated
Subjectis the username used during the login process (more later). Here's the action code from HelloWorld with the three system calls (the reason for the required permissions) in bold :
Subject.doAsPrivileged(lc.getSubject(), new PrivilegedAction() { public Object run() { System.out.println("\nYour java.home property: " +System.getProperty("java.home") ); System.out.println("\nYour user.home property: " +System.getProperty("user.home") ); File f = new File("foo.txt"); System.out.print("\nfoo.txt does "); if (!f.exists() ) System.out.print("not "); System.out.println("exist in your current directory"); System.out.println("\nOh, by the way ..."); try { Thread.currentThread().sleep(2000); } catch (Exception e) { // ignore } System.out.println("\n\nHello World!\n"); return null; } }, null);When running the HelloWorld program, use various usernames and alter jaas.policy accordingly. There is no need to alter java2.policy . Also, create a file called foo.txt in the test directory to test the last system call.
Examine Source Files The LoginModule,
HWLoginModule, authenticates any user who enters the correct password (case sensitive): Go JAAS .
The HelloWorld application permits users three attempts to do so. When Go JAAS is correctly entered, an
HWPrincipalwith a name equal the the username is added to the authenticated
Subject.
The Principal class,
HWPrincipal, represents a Principal based on the username entered. It is this name that is important when granting permissions to authenticated Subjects.
The main application,
HelloWorld, first creates a
LoginContextbased on a configuration entry with the name helloWorld . The configuration file has already been discussed. Callbacks are used to retrieve user input. Look at the
MyCallbackHandlerclass located in the HelloWorld.java file to see this process.
LoginContext lc = null; try { lc = new LoginContext("helloWorld", new MyCallbackHandler()); } catch (LoginException le) { le.printStackTrace(); System.exit(-1); }The user enters a username/password (up to three times) and if Go JAAS is entered as the password, then the Subject is authenticated (
HWLoginModuleadds a
HWPrincipalto the Subject).
As mentioned previously, work is then performed as the authenticated Subject.
Run HelloWorld Test
To run the HelloWorld program, first change to the test directory. The configuration and policy files will need to be loaded. See Implementation for the correct properties to set either in java.security or on the command line. The latter method will be discussed here.
The following command has been broken up into several lines for clarity. Enter as one continuous command.
java -Djava.security.manager= -Djava.security.auth.login.config=.\jaas.config -Djava.security.policy=.\java2.policy -Djava.security.auth.policy=.\jaas.policy HelloWorldNote: the use of ".\filename" for the policy files is necessary because each user's test directory canonical path will vary. If desired, substitute "." with the path to the test directory. For example, if the test directory is "c:\test\hello", then the first file is changed to:
-Djava.security.auth.login.config=c:\test\hello\jaas.configIf the policy files are not found, a
SecurityExceptionwill be thrown. Otherwise, information concerning your java.home and user.home properties will be displayed. Also, the existence of a file called foo.txt in your test directory will be checked. Finally, the ubiquitous "Hello World" message is displayed.
Having Fun With HelloWorld
Rerun HelloWorld as many times as you like. It has already been suggested to vary the username/passwords entered, change the configuration file entries, change the policy file permissions, and to even add (stack) additional LoginModules to the helloWorld configuration entry. You could add codebase fields to the policy files too.
Finally, try running the program without a SecurityManager to see how it works if you run into problems.
Appendix A: JAAS Settings in the java.security Security Properties File
Below is a copy of the
java.securityfile that appears in every Java 2 installation. This file appears in the
lib/security(
lib\securityon Windows®) directory of the Java 2 runtime. Thus, if the Java 2 runtime is installed in a directory called
jdk1.3, the file is
-
jdk1.3/lib/security/java.security
(Unix) -
jdk1.3\lib\security\java.security
(Windows)
java.security:
- Authentication Properties
-
login.configuration.provider
-
login.policy.url.n
-
- Authorization Properties
-
auth.policy.provider
-
auth.policy.url.n
-
The new JAAS properties are located at the end of this file:
# # This is the "master security properties file". # # In this file, various security properties are set for use by # java.security classes. This is where users can statically register # Cryptography Package Providers ("providers" for short). The term # "provider" refers to a package or set of packages that supply a # concrete implementation of a subset of the cryptography aspects of # the Java Security API. A provider may, for example, implement one or # more digital signature algorithms or message digest algorithms. # # Each provider must implement a subclass of the Provider class. # To register a provider in this master security properties file, # specify the Provider subclass name and priority in the format # # security.provider.n=className # # This declares a provider, and specifies its preference # order n. The preference order is the order in which providers are # searched for requested algorithms (when no specific provider is # requested). The order is 1-based; 1 is the most preferred, followed # by 2, and so on. # # className must specify the subclass of the Provider class whose # constructor sets the values of various properties that are required # for the Java Security API to look up the algorithms or other # facilities implemented by the provider. # # There must be at least one provider specification in java.security. # There is a default provider that comes standard with the JDK. It # is called the "SUN" provider, and its Provider subclass # named Sun appears in the sun.security.provider package. Thus, the # "SUN" provider is registered via the following: # # security.provider.1=sun.security.provider.Sun # # (The number 1 is used for the default provider.) # # Note: Statically registered Provider subclasses are instantiated # when the system is initialized. Providers can be dynamically # registered instead by calls to either the addProvider or # insertProviderAt method in the Security class. # # List of providers and their preference orders (see above): # security.provider.1=sun.security.provider.Sun # # Class to instantiate as the system Policy. This is the name of the class # that will be used as the Policy object. # policy.provider=sun.security.provider.PolicyFile # The default is to have a single system-wide policy file, # and a policy file in the user's home directory. policy.url.1=file:${java.home}/lib/security/java.policy policy.url.2=file:${user.home}/.java.policy # whether or not we expand properties in the policy file # if this is set to false, properties (${...}) will not be expanded in policy # files. policy.expandProperties=true # whether or not we allow an extra policy to be passed on the command line # with -Djava.security.policy=somefile. Comment out this line to disable # this feature. policy.allowSystemProperty=true # whether or not we look into the IdentityScope for trusted Identities # when encountering a 1.1 signed JAR file. If the identity is found # and is trusted, we grant it AllPermission. policy.ignoreIdentityScope=false # # Default keystore type. # keystore.type=jks # # Class to instantiate as the system scope: # system.scope=sun.security.provider.IdentityDatabase ############################################################################## # # Java Authentication and Authorization Service (JAAS) # properties and policy files: # # Class to instantiate as the system Configuration for authentication. # This is the name of the class that will be used as the Authentication # Configuration object. # login.configuration.provider=com.ibm.security.auth.login.ConfigFile # The default is to have a system-wide login configuration file found in # the user's home directory. For multiple files, the format is similar to # that of CodeSource-base policy files above, that is policy发表评论
-
IntelliJ IDEA Live Templates for Unit Testing
2017-12-12 17:29 362http://vansande.org/2015/03 ... -
memory management in java
2017-12-07 15:25 337https://www.journaldev.com/28 ... -
Easiest way to read write files in java 8
2017-10-25 15:46 465Path path = Paths.get(getClas ... -
Tomcat 在启动时开启调试
2017-03-31 11:47 675很容量找到怎么在tomcat中远程调试的文章。如 http ... -
java读取文件内容
2013-11-19 15:37 559//将要读的文件文件放在resources/xml/目 ... -
Will android (java) UUID.randomUUID() return repeated UUIDs?
2013-11-19 06:11 2310Theoretically, I don't think ... -
将一个文件由gbk 转成 utf-8
2010-08-11 21:02 1522public void transform(String f ... -
java Serialization
2009-06-29 11:09 697http://www.blogjava.net/orangel ... -
java读取文件的路径如何找的
2009-06-04 13:58 1537is = getClass().getClassLoad ... -
要到另一个目录下运行ant, .bat文件中调用ant
2009-05-21 09:50 3462<ant antfile="build.xml ... -
一个生成json字符串的类
2009-04-16 13:08 954public class UserProjWorkloadQu ... -
运用Calendar进行java日期处理
2009-03-21 16:58 3275取得时间点所在的日的起始时间和结束时间(From Quartz ... -
ant 用户手册
2009-01-07 11:04 729http://ant.apache.org/manual/in ... -
Thread join() 用法
2008-11-11 20:36 1952Thread[] cThreads = new Thread[ ... -
利用Serialization实现对象深拷贝
2007-10-25 22:54 887java 代码 private PersonA ... -
Form-Letter Programming
2007-09-10 20:54 943Form-Letter Programming VS Mess ... -
StringBuffer VS StringBuilder
2007-09-08 23:05 1373现在看了,知道了,太简单了,其实说白了,StringB ... -
使用java.util.Calendar返回间隔天数
2007-07-29 13:32 1758java 代码 ** * Calc ... -
由xml和Document的标准操作
2007-07-09 22:49 1004xml 到Documetn java 代码 p ... -
利用java.util.Properties从properties文件读入properties
2007-07-02 18:29 1148java 代码 // reads the pr ...
相关推荐
Java Authentication and Authorization Service (JAAS) 是Java平台提供的一种安全框架,用于实现用户身份验证和权限管理。这个框架使得开发者可以轻松地在Java应用程序中集成安全性,而不必深入理解底层的复杂安全...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全性的核心组件,它为开发者提供了一种机制来处理用户身份验证和权限控制。这个服务允许应用程序执行基于角色的安全性,这意味着用户的...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于实现用户身份验证和权限管理的核心组件。这个"Java JAAS安全认证 demo"是一个示例项目,旨在帮助开发者理解如何在Java应用中实施安全认证...
Java Authentication and Authorization Service (JAAS) 是 Java 平台中用于安全管理的重要组件,它提供了一种框架,使得应用程序可以进行用户身份验证和权限控制。在本文中,我们将深入探讨 JAAS 的核心概念、工作...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全性的框架,主要用于用户身份验证和权限授权。在Java应用程序中,尤其是服务器端应用,确保只有合法的用户能够访问资源是至关重要的。...
### JAAS登录验证知识点 #### 一、JAAS概述 Java Authentication and Authorization Service(JAAS)是Java平台提供的一种安全框架,它允许开发者为应用程序添加认证和授权功能。与传统的基于容器的身份验证不同,...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全性的关键组件,它提供了一种框架,使得应用程序能够实现用户身份验证和权限管理。在这个教程中,我们将深入探讨JAAS的核心概念、工作...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全性的关键组件,它提供了一种标准框架来实现用户身份验证和授权。在Web应用程序中,JAAS被用来控制对资源的访问,确保只有经过验证的用户...
**Java Authentication and Authorization Service (JAAS) 认证在Mac版Tomcat中的应用** Java Authentication and Authorization Service (JAAS) 是Java平台的核心组件,用于提供安全的用户认证和权限管理。在Mac版...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全认证和授权的核心组件。它为开发者提供了一种标准的方式来管理用户的身份验证和访问控制,从而确保应用程序的安全性。在本精讲中,我们...
标题 "websphere 6 JAAS登陆例子" 描述了一个在Websphere 6版本中集成LDAP用户和实现Single Sign-On (SSO)的实践案例。这个主题涉及到Java Authentication and Authorization Service (JAAS)的安全框架,以及它如何...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全性的关键组件,它提供了一种框架,用于在Java应用程序中实现认证(Authentication)和授权(Authorization)。`jaas.jar` 文件是这个...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全管理的框架,它是Java Cryptography Extension (JCE) 安全框架的重要补充。JAAS的主要目标是提供用户认证和授权服务,确保应用程序能...
### 在JAAS基础上的Java安全编程 #### 一、引言 随着互联网技术的发展和企业对数据安全的重视,Java作为一种广泛应用的编程语言,在安全领域扮演着越来越重要的角色。JAAS(Java Authentication and Authorization...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全认证和授权的核心组件。它提供了一个框架,使得应用程序可以通过统一的方式来处理用户身份验证和权限控制。JAAS的主要目标是简化应用的...
### 基于JAAS的Java安全编程 #### JAAS概览 JAAS(Java Authentication and Authorization Service,Java认证与授权服务)是Sun Microsystems为Java 2平台开发的一套安全框架扩展,旨在加强Java应用程序的安全性。...
### JAAS身份验证技术入门详解 #### 一、JAAS概览 JAAS,全称为Java Authentication and Authorization Service(Java认证与授权服务),是Java Standard Edition(Java SE)中的一个核心组成部分,旨在为Java应用...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于实现用户认证和权限授权的一个核心组件。它为开发者提供了一种灵活的方式来实现安全控制,确保只有经过验证和授权的用户能够访问敏感资源或...