在 Java 中,我可以通过调用 java.security.AccessController.doPrivileged() 来提高权限。
如何提高 kotlin 协程的权限?
示例:当我调用程序时
import java.security.AccessControlContext
import java.security.AccessController
import java.security.PrivilegedAction
import java.security.ProtectionDomain
import kotlinx.coroutines.runBlocking
object Privileged {
private fun checkDirect(expectAllowed: Boolean) {
try {
System.getProperty("allowed")
if (expectAllowed) {
println("expected: allowed")
}
else {
println("UNEXPECTED: allowed")
}
} catch (e: SecurityException) {
if (expectAllowed) {
println("UNEXPECTED: forbidden")
}
else {
println("expected: forbidden")
}
}
}
private suspend fun checkSuspend(expectAllowed: Boolean) {
checkDirect(expectAllowed)
}
@JvmStatic
fun main(vararg argv: String) {
// drop privileges
AccessController.doPrivileged(
PrivilegedAction {
// privileges are all dropped here
// 1. direct functions:
// this check will fail
checkDirect(false)
// raise privilege
AccessController.doPrivileged(
PrivilegedAction {
// privileges are all raised here
// so this check will succeed
checkDirect(true)
}
)
// 2. suspend functions:
runBlocking {
// this call will fail
checkSuspend(false)
// FIXME: How to call checkSuspend(true) with raised privileges?
}
},
AccessControlContext(arrayOf(ProtectionDomain(null, null)))
)
}
}
java.policy在java -Djava.security.manager -Djava.security.policy=java.policy Privileged
哪里
grant {
permission java.security.AllPermission;
};
我明白了
expected: forbidden
expected: allowed
expected: forbidden
什么是 AccessController.doPrivileged() 的等价物,用于以提升的权限调用 checkSuspend(参见程序代码中的 FIXME)?