
|
Authorization Authorization is about allowing or denying access to resources to a particular subject (a user, a group, a company, ...). When a subject is authenticated, it is augmented with one or more principals that identify the subject for one or more resources, for example a social security number for one resource or a role of an administrator for another. A subject can also have credentials associated with them, any Java objects that contains security-related information about the subject, for example a certificate or a password. To go ahead with this example, first read the authentication example. In the following example, the authentication example will be augmented with a section that is only executed when it is permitted to do so by a particular principal, in our example "johndoe". As opposed to specifying the principals and permissions in a policy file (see How do I use authorization with JAAS (declarative)) it is done programmatically. We also have another policy file that grants permissions to read and write System properties (needed by the Swing DialogCallbackHandler), to create a LoginContext (necessary for authentication), to execute a doAsPrivileged method (necessary for executing sensitive code that requires principal permissions) and to modify principals (necessary when we add a principal to the subject). jaasmain.policy:
Our module that encapsulates code to do authentication has not changed from the authentication example. UsernamePasswordLoginModule.java:
Our passwd "database" textfile has not changed from the authentication example. passwd:
Our MyPrincipal class has also not changed from the authentication example. MyPrincipal.java:
The code that is to be executed based on user authentication must be inside the run method of a class that implements java.security.PrivilegedAction. WriteFileAction.java:
We want this code to be executed only when a specified principal is running it ("johndoe" as specified in the policy file). We enforce this by calling this code indirectly through the method doAs or doAsPrivileged. The difference between the two is described here. Main.java:
To run the code, you need to specify the policy files (or change the default java.policy one):
Running the code with username="johndoe", password="sdefujm" results in:
Running the code with username="janedoe", password="yuymndee" (another authenticated user, but not authorized) results in:
Notice that "janedoe" is correctly authenticated, but not authorized to run the privileged code as that principal is not specified in the policy file accesscontrol.policy. Further Information Author of answer: Joris Van den Bogaert Comments to this answer are only viewable by members. Login or become a member! |