BAEL-1529 Intro to the Java SecurityManager (#7697)
This commit is contained in:
committed by
Grzegorz Piwowarek
parent
c4a1b44b39
commit
73743acb30
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.security.manager;
|
||||
|
||||
import java.security.BasicPermission;
|
||||
|
||||
public class CustomPermission extends BasicPermission {
|
||||
public CustomPermission(String name) {
|
||||
super(name);
|
||||
}
|
||||
|
||||
public CustomPermission(String name, String actions) {
|
||||
super(name, actions);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.security.manager;
|
||||
|
||||
public class Service {
|
||||
|
||||
public static final String OPERATION = "my-operation";
|
||||
|
||||
public void operation() {
|
||||
SecurityManager securityManager = System.getSecurityManager();
|
||||
if (securityManager != null) {
|
||||
securityManager.checkPermission(new CustomPermission(OPERATION));
|
||||
}
|
||||
System.out.println("Operation is executed");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
new Service().operation();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.baeldung.security.manager;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.net.URL;
|
||||
import java.security.AccessControlException;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public class SecurityManagerUnitTest {
|
||||
|
||||
@Test(expected = AccessControlException.class)
|
||||
public void whenSecurityManagerIsActive_thenNetworkIsNotAccessibleByDefault() throws Exception {
|
||||
doTest(() -> {
|
||||
new URL("http://www.google.com").openConnection().connect();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@Test(expected = AccessControlException.class)
|
||||
public void whenUnauthorizedClassTriesToAccessProtectedOperation_thenAnExceptionIsThrown() throws Exception {
|
||||
doTest(() -> {
|
||||
new Service().operation();
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
private void doTest(Callable<Void> action) throws Exception {
|
||||
System.setSecurityManager(new SecurityManager());
|
||||
try {
|
||||
action.call();
|
||||
} finally {
|
||||
System.setSecurityManager(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user