How do I add a new RuntimePermission security policy at runtime in Java?

I want to add at runtime a new RuntimePermission to the set of already existing permissions ( java.policy ). Here is my code:

ProtectionDomain domain = MyClass.class.getProtectionDomain();
        final PermissionCollection domainPerms = domain.getPermissions();
        Enumeration<Permission> oldPerms = domainPerms.elements();
        PermissionCollection newPerms = new Permissions();

        //add the old permissions to
        while (oldPerms.hasMoreElements()) {
            newPerms.add(oldPerms.nextElement());
        }
        //add my new permission
        RuntimePermission rtPermission = new RuntimePermission("accessDeclaredMembers");
        newPerms.add(rtPermission);

      

..

But how can I use the object newPerms

?

Also I tried to add a new permission to oldPerms

, but since oldPerms

read only I get a nice security exception.

Thanks!

0


a source to share


1 answer


Types Permissions

have a very strange API, although it shouldn't be surprising that you can't modify an object that has been set read-only. ProtectionDomain

must be unchanged.



However, since 1.4ish, you can have "dynamic" ProtectionDomain

deferred to the current one Policy

. However, trying to change permissions on the fly is not something I would recommend as it doesn't make much sense. it's better to build APIs with the ability to approach - SecurityManager

there is only paper over the cracks in bad APIs.

0


a source







All Articles