Search code examples
javasecuritypermissionspolicy

How to use custom PolicySpi


I'm trying to implement a custom java.security.Permission type, which should be checked at runtime (so no policy file, but in code). This checking is done by a java.security.Policy. I understood I should implement my own java.security.PolicySpi for this.

I cannot find any explanation on how to initialise and use a PolicySpi, or is there a better way to do this?


Solution

  • Checking permissions

    In your question you stated that you then want to check the permission with java.security.Policy, but without using a spi.policy file.

    From the PolicySpi API, you can see that a PolicySpi object features 4 methods:

    1. engineGetPermissions(CodeSource codesource)
    2. engineGetPermissions(ProtectionDomain domain)
    3. engineImplies(ProtectionDomain domain, Permission permission)
    4. engineRefresh()

    However, you might not need PolicySpi as there are easier solutions to check permissions.

    See:

    Since you haven't specified what kind of permission you will grant, I will assume it is a permission concerning a java.security.CodeSource object.

    To check all current permissions for a file:

    public static void main(String[] args) {
    
        CodeSource source;
    
        try {
          source = new CodeSource(new URL("file:/c:/*"), (java.security.cert.Certificate[]) null);
    
          Policy policy = Policy.getPolicy();
          System.out.println(policy.getPermissions(source));
    
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    

    A nice example for the SecurityManager checkPermission() is this tutorial.

    For checking specific FilePermissions, you can use:

    FilePermission perm = new FilePermission("path/file", "read");
    AccessController.checkPermission(perm);
    

    Granting permissions

    Granting permissions at runtime can be done with java.lang.RuntimePermission.

    For other examples of how to grant permissions to a file, I suggest you read the following:


    That should bring you a long way! Good luck!