本文整理匯總了Java中javax.security.auth.Subject.doAs方法的典型用法代碼示例。如果您正苦於以下問題:Java Subject.doAs方法的具體用法?Java Subject.doAs怎麽用?Java Subject.doAs使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類javax.security.auth.Subject
的用法示例。
在下文中一共展示了Subject.doAs方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: main
import javax.security.auth.Subject; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
// We don't care about clock difference
new FileOutputStream("krb5.conf").write(
"[libdefaults]\nclockskew=999999999".getBytes());
System.setProperty("java.security.krb5.conf", "krb5.conf");
Config.refresh();
Subject subj = new Subject();
KerberosPrincipal kp = new KerberosPrincipal(princ);
KerberosKey kk = new KerberosKey(
kp, key, EncryptedData.ETYPE_AES128_CTS_HMAC_SHA1_96, 0);
subj.getPrincipals().add(kp);
subj.getPrivateCredentials().add(kk);
Subject.doAs(subj, new PrivilegedExceptionAction() {
public Object run() throws Exception {
GSSManager man = GSSManager.getInstance();
GSSContext ctxt = man.createContext(man.createCredential(
null, GSSCredential.INDEFINITE_LIFETIME,
GSSUtil.GSS_KRB5_MECH_OID, GSSCredential.ACCEPT_ONLY));
return ctxt.acceptSecContext(token, 0, token.length);
}
});
}
示例2: validateServiceTicket
import javax.security.auth.Subject; //導入方法依賴的package包/類
public static String validateServiceTicket(Subject subject, final byte[] serviceTicket)
throws GSSException, IllegalAccessException, NoSuchFieldException, ClassNotFoundException,
PrivilegedActionException {
// Kerberos version 5 OID
Oid krb5Oid = KerberosUtils.getOidInstance("GSS_KRB5_MECH_OID");
// Accept the context and return the client principal name.
return Subject.doAs(subject, new PrivilegedExceptionAction<String>() {
@Override
public String run() throws Exception {
String clientName = null;
// Identify the server that communications are being made to.
GSSManager manager = GSSManager.getInstance();
GSSContext context = manager.createContext((GSSCredential) null);
context.acceptSecContext(serviceTicket, 0, serviceTicket.length);
clientName = context.getSrcName().toString();
return clientName;
}
});
}
示例3: main
import javax.security.auth.Subject; //導入方法依賴的package包/類
public static void main(String[] args) throws Exception {
System.out.println("Thrift2 Demo");
System.out.println("Usage: DemoClient [host=localhost] [port=9090] [secure=false]");
System.out.println("This demo assumes you have a table called \"example\" with a column family called \"family1\"");
// use passed in arguments instead of defaults
if (args.length >= 1) {
host = args[0];
}
if (args.length >= 2) {
port = Integer.parseInt(args[1]);
}
if (args.length >= 3) {
secure = Boolean.parseBoolean(args[2]);
}
final DemoClient client = new DemoClient();
Subject.doAs(getSubject(),
new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws Exception {
client.run();
return null;
}
});
}
示例4: createSaslServer
import javax.security.auth.Subject; //導入方法依賴的package包/類
private void createSaslServer(String mechanism) throws IOException {
this.saslMechanism = mechanism;
if (!ScramMechanism.isScram(mechanism))
callbackHandler = new SaslServerCallbackHandler(jaasContext, kerberosNamer);
else
callbackHandler = new ScramServerCallbackHandler(credentialCache.cache(mechanism, ScramCredential.class));
callbackHandler.configure(configs, Mode.SERVER, subject, saslMechanism);
if (mechanism.equals(SaslConfigs.GSSAPI_MECHANISM)) {
saslServer = createSaslKerberosServer(callbackHandler, configs, subject);
} else {
try {
saslServer = Subject.doAs(subject, new PrivilegedExceptionAction<SaslServer>() {
public SaslServer run() throws SaslException {
// 調用createSaslServer
return Sasl.createSaslServer(saslMechanism, "kafka", host, configs, callbackHandler);
}
});
} catch (PrivilegedActionException e) {
throw new SaslException("Kafka Server failed to create a SaslServer to interact with a client during session authentication", e.getCause());
}
}
}
示例5: createSaslToken
import javax.security.auth.Subject; //導入方法依賴的package包/類
private byte[] createSaslToken(final byte[] saslToken, boolean isInitial) throws SaslException {
if (saslToken == null)
throw new SaslException("Error authenticating with the Kafka Broker: received a `null` saslToken.");
try {
// 初始Response的處理
if (isInitial && !saslClient.hasInitialResponse())
return saslToken;
else
return Subject.doAs(subject, new PrivilegedExceptionAction<byte[]>() {
public byte[] run() throws SaslException {
// 調用evalueteChallenge方法處理Challenge信息
return saslClient.evaluateChallenge(saslToken);
}
});
} catch (PrivilegedActionException e) {
String error = "An error: (" + e + ") occurred when evaluating SASL token received from the Kafka Broker.";
// Try to provide hints to use about what went wrong so they can fix their configuration.
// TODO: introspect about e: look for GSS information.
final String unknownServerErrorText =
"(Mechanism level: Server not found in Kerberos database (7) - UNKNOWN_SERVER)";
if (e.toString().contains(unknownServerErrorText)) {
error += " This may be caused by Java's being unable to resolve the Kafka Broker's" +
" hostname correctly. You may want to try to adding" +
" '-Dsun.net.spi.nameservice.provider.1=dns,sun' to your client's JVMFLAGS environment." +
" Users must configure FQDN of kafka brokers when authenticating using SASL and" +
" `socketChannel.socket().getInetAddress().getHostName()` must match the hostname in `principal/[email protected]`";
}
error += " Kafka Client will go to AUTH_FAILED state.";
//Unwrap the SaslException inside `PrivilegedActionException`
throw new SaslException(error, e.getCause());
}
}
示例6: main
import javax.security.auth.Subject; //導入方法依賴的package包/類
public static void main (String args[]) throws Exception {
ObjectName[] mbeanNames = new ObjectName[6];
ObservedObject[] monitored = new ObservedObject[6];
ObjectName[] monitorNames = new ObjectName[6];
Monitor[] monitor = new Monitor[6];
String[] principals = { "role1", "role2" };
String[] attributes = { "Integer", "Double", "String" };
try {
echo(">>> CREATE MBeanServer");
MBeanServer server = MBeanServerFactory.newMBeanServer();
for (int i = 0; i < 6; i++) {
mbeanNames[i] =
new ObjectName(":type=ObservedObject,instance=" + i);
monitored[i] = new ObservedObject();
echo(">>> CREATE ObservedObject = " + mbeanNames[i].toString());
server.registerMBean(monitored[i], mbeanNames[i]);
switch (i) {
case 0:
case 3:
monitorNames[i] =
new ObjectName(":type=CounterMonitor,instance=" + i);
monitor[i] = new CounterMonitor();
break;
case 1:
case 4:
monitorNames[i] =
new ObjectName(":type=GaugeMonitor,instance=" + i);
monitor[i] = new GaugeMonitor();
break;
case 2:
case 5:
monitorNames[i] =
new ObjectName(":type=StringMonitor,instance=" + i);
monitor[i] = new StringMonitor();
break;
}
echo(">>> CREATE Monitor = " + monitorNames[i].toString());
server.registerMBean(monitor[i], monitorNames[i]);
monitor[i].addObservedObject(mbeanNames[i]);
monitor[i].setObservedAttribute(attributes[i % 3]);
monitor[i].setGranularityPeriod(500);
final Monitor m = monitor[i];
Subject subject = new Subject();
echo(">>> RUN Principal = " + principals[i / 3]);
subject.getPrincipals().add(new JMXPrincipal(principals[i / 3]));
PrivilegedAction<Void> action = new PrivilegedAction<Void>() {
public Void run() {
m.start();
return null;
}
};
Subject.doAs(subject, action);
}
while(!testPrincipals(monitored, monitorNames, monitor, principals));
} finally {
for (int i = 0; i < 6; i++)
if (monitor[i] != null)
monitor[i].stop();
}
}
示例7: run
import javax.security.auth.Subject; //導入方法依賴的package包/類
@Override
public Object run() throws Exception {
Utils.readFile(filename);
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
ReadPropertyExceptionAction readProperty =
new ReadPropertyExceptionAction();
return Subject.doAs(subject, readProperty);
}
示例8: testUGIUnderNonHadoopContext
import javax.security.auth.Subject; //導入方法依賴的package包/類
/**
* Test for the case that UserGroupInformation.getCurrentUser()
* is called when the AccessControlContext has a Subject associated
* with it, but that Subject was not created by Hadoop (ie it has no
* associated User principal)
*/
@Test (timeout = 30000)
public void testUGIUnderNonHadoopContext() throws Exception {
Subject nonHadoopSubject = new Subject();
Subject.doAs(nonHadoopSubject, new PrivilegedExceptionAction<Void>() {
@Override
public Void run() throws IOException {
UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
assertNotNull(ugi);
return null;
}
});
}
示例9: main
import javax.security.auth.Subject; //導入方法依賴的package包/類
public static void main(String args[]) {
Subject subject = new Subject();
subject.getPrincipals().add(new X500Principal("CN=Duke"));
Subject anotherSubject = new Subject();
anotherSubject.getPrincipals().add(new X500Principal("CN=Java"));
ReadFromFileAction readFromFile
= new ReadFromFileAction(NestedActions.file, anotherSubject);
WriteToFileAction writeToFile
= new WriteToFileAction(NestedActions.file, readFromFile);
Subject.doAs(subject, writeToFile);
}
示例10: main
import javax.security.auth.Subject; //導入方法依賴的package包/類
public static void main(String[] args) {
Subject subject = new Subject();
final Set principals = subject.getPrincipals();
principals.add(new X500Principal("CN=Alice"));
new Thread() {
public void run() {
Principal last = new X500Principal("CN=Bob");
for (int i = 0; !finished; i++) {
Principal next = new X500Principal("CN=Bob" + i);
principals.add(next);
principals.remove(last);
last = next;
}
}
}.start();
for (int i = 0; i < 1000; i++) {
Subject.doAs(
subject,
new PrivilegedAction() {
public Object run() {
return Subject.doAs(
new Subject(true,
Collections.singleton(
new X500Principal("CN=Claire")),
Collections.EMPTY_SET,
Collections.EMPTY_SET),
new PrivilegedAction() {
public Object run() {
return null;
}
});
}
});
}
finished = true;
}
示例11: main
import javax.security.auth.Subject; //導入方法依賴的package包/類
public static void main(String args[]) {
Subject subject = new Subject();
subject.getPrincipals().add(new X500Principal("CN=Duke"));
WriteToFileNegativeAction writeToFile
= new WriteToFileNegativeAction(NestedActions.file);
Subject.doAs(subject, writeToFile);
}
示例12: run
import javax.security.auth.Subject; //導入方法依賴的package包/類
@Override
public Object run() throws Exception {
Utils.writeFile(filename);
AccessControlContext acc = AccessController.getContext();
Subject subject = Subject.getSubject(acc);
ReadFromFileExceptionAction readFromFile =
new ReadFromFileExceptionAction(filename);
return Subject.doAs(subject, readFromFile);
}
示例13: doAs
import javax.security.auth.Subject; //導入方法依賴的package包/類
/**
* Does something using the Subject inside
* @param action the action
* @param in the input byte
* @return the output byte
* @throws java.lang.Exception
*/
public byte[] doAs(final Action action, final byte[] in) throws Exception {
try {
return Subject.doAs(s, new PrivilegedExceptionAction<byte[]>() {
@Override
public byte[] run() throws Exception {
return action.run(Context.this, in);
}
});
} catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
示例14: createSaslToken
import javax.security.auth.Subject; //導入方法依賴的package包/類
private byte[] createSaslToken(final byte[] saslToken) throws SaslException {
if (saslToken == null) {
// TODO: introspect about runtime environment (such as jaas.conf)
saslState = SaslState.FAILED;
throw new SaslException("Error in authenticating with a Zookeeper Quorum member: the quorum member's saslToken is null.");
}
Subject subject = login.getSubject();
if (subject != null) {
synchronized(login) {
try {
final byte[] retval =
Subject.doAs(subject, new PrivilegedExceptionAction<byte[]>() {
public byte[] run() throws SaslException {
LOG.debug("saslClient.evaluateChallenge(len="+saslToken.length+")");
return saslClient.evaluateChallenge(saslToken);
}
});
return retval;
}
catch (PrivilegedActionException e) {
String error = "An error: (" + e + ") occurred when evaluating Zookeeper Quorum Member's " +
" received SASL token.";
// Try to provide hints to use about what went wrong so they can fix their configuration.
// TODO: introspect about e: look for GSS information.
final String UNKNOWN_SERVER_ERROR_TEXT =
"(Mechanism level: Server not found in Kerberos database (7) - UNKNOWN_SERVER)";
if (e.toString().indexOf(UNKNOWN_SERVER_ERROR_TEXT) > -1) {
error += " This may be caused by Java's being unable to resolve the Zookeeper Quorum Member's" +
" hostname correctly. You may want to try to adding" +
" '-Dsun.net.spi.nameservice.provider.1=dns,sun' to your client's JVMFLAGS environment.";
}
error += " Zookeeper Client will go to AUTH_FAILED state.";
LOG.error(error);
saslState = SaslState.FAILED;
throw new SaslException(error);
}
}
}
else {
throw new SaslException("Cannot make SASL token without subject defined. " +
"For diagnosis, please look for WARNs and ERRORs in your log related to the Login class.");
}
}
示例15: testAuthenticatedClientsAllowed
import javax.security.auth.Subject; //導入方法依賴的package包/類
@Test public void testAuthenticatedClientsAllowed() throws Exception {
Assume.assumeThat("Test disabled on Windows", File.separatorChar, is('/'));
// Create the subject for the client
final Subject clientSubject = AvaticaJaasKrbUtil.loginUsingKeytab(
SpnegoTestUtil.CLIENT_PRINCIPAL, clientKeytab);
final Set<Principal> clientPrincipals = clientSubject.getPrincipals();
// Make sure the subject has a principal
assertFalse(clientPrincipals.isEmpty());
// Get a TGT for the subject (might have many, different encryption types). The first should
// be the default encryption type.
Set<KerberosTicket> privateCredentials =
clientSubject.getPrivateCredentials(KerberosTicket.class);
assertFalse(privateCredentials.isEmpty());
KerberosTicket tgt = privateCredentials.iterator().next();
assertNotNull(tgt);
LOG.info("Using TGT with etype: {}", tgt.getSessionKey().getAlgorithm());
// The name of the principal
final String principalName = clientPrincipals.iterator().next().getName();
// Run this code, logged in as the subject (the client)
byte[] response = Subject.doAs(clientSubject, new PrivilegedExceptionAction<byte[]>() {
@Override public byte[] run() throws Exception {
// Logs in with Kerberos via GSS
GSSManager gssManager = GSSManager.getInstance();
Oid oid = new Oid(SpnegoTestUtil.JGSS_KERBEROS_TICKET_OID);
GSSName gssClient = gssManager.createName(principalName, GSSName.NT_USER_NAME);
GSSCredential credential = gssManager.createCredential(gssClient,
GSSCredential.DEFAULT_LIFETIME, oid, GSSCredential.INITIATE_ONLY);
// Passes the GSSCredential into the HTTP client implementation
final AvaticaCommonsHttpClientSpnegoImpl httpClient =
new AvaticaCommonsHttpClientSpnegoImpl(httpServerUrl, credential);
return httpClient.send(new byte[0]);
}
});
// We should get a response which is "OK" with our client's name
assertNotNull(response);
assertEquals("OK " + SpnegoTestUtil.CLIENT_PRINCIPAL,
new String(response, StandardCharsets.UTF_8));
}