How to find the weblogic jmx attributes for a objectname - java

I am writing simple client application to connect to weblogic and list all the libraries that a webapp is depending on.However, I am having difficulty in finding the right attributes for a objectname. For example,
If you look at the below sample code given on oracle.com to connect MBeanServer
public static void initConnection(String hostname, String portString,
String username, String password) throws IOException,
MalformedURLException {
String protocol = "t3";
Integer portInteger = Integer.valueOf(portString);
int port = portInteger.intValue();
String jndiroot = "/jndi/";
String mserver = "weblogic.management.mbeanservers.edit";
JMXServiceURL serviceURL = new JMXServiceURL(protocol, hostname, port,
jndiroot + mserver);
Hashtable h = new Hashtable();
h.put(Context.SECURITY_PRINCIPAL, username);
h.put(Context.SECURITY_CREDENTIALS, password);
h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES,
"weblogic.management.remote");
connector = JMXConnectorFactory.connect(serviceURL, h);
connection = connector.getMBeanServerConnection();
}
public ObjectName startEditSession() throws Exception {
// Get the object name for ConfigurationManagerMBean.
ObjectName cfgMgr = (ObjectName) connection.getAttribute(service,
"ConfigurationManager");
// Instruct MBeanServerConnection to invoke
// ConfigurationManager.startEdit(int waitTime int timeout).
// The startEdit operation returns a handle to DomainMBean, which is
// the root of the edit hierarchy.
ObjectName domainConfigRoot = (ObjectName)
connection.invoke(cfgMgr,"startEdit",
new Object[] { new Integer(60000),
new Integer(120000) }, new String[] { "java.lang.Integer",
"java.lang.Integer" });
if (domainConfigRoot == null) {
// Couldn't get the lock
throw new Exception("Somebody else is editing already");
}
return domainConfigRoot;
}
The line
ObjectName cfgMgr = (ObjectName) connection.getAttribute(service,
"ConfigurationManager");
Is referring to a JMX attribute ConfigurationManger. How can we find all the attributes that are under a given objectname in weblogic?
Thanks for your help!!

Nevermind! I found the solution.
You get attributes for a ObjectName by calling getBeanInfo on the ServerConnection!
Example:
MBeanAttributeInfo[] beanInfo = (connection.getMBeanInfo(objectName)).getAttributes();
for(MBeanAttributeInfo info:beanInfo)
System.out.println(info.getType()+" "+info.getName());

Maybe the WebLogic Classloader Analysis Tool (CAT) can give additional insight out of the box ...

Related

getting error while running the web service client and proxy, SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml in JDeveloper 12c

i am developing the java application in JDeveloper.which is use to connect with oracle sales cloud web services so for this i have did the following steps.
step 1: created the custom Application
step 2: Then i have generated the client from wsdl using web service client and proxy.
its generated the successfully and i have added the credential to main class . this is my main class.
public class PersonServiceSoapHttpPortClient {
private static final AddressingVersion WS_ADDR_VER = AddressingVersion.W3C;
public static void main(String[] args) throws Exception{
PersonService_Service personService_Service = new PersonService_Service();
PersonService personService = personService_Service.getPersonServiceSoapHttpPort();
// Configure credential providers
Map<String, Object> requestContext = ((BindingProvider) personService).getRequestContext();
try {
setPortCredentialProviderList(requestContext);
} catch (Exception ex) {
ex.printStackTrace();
}
// Add your code to call the desired methods.
FindCriteria findCriteria=new FindCriteria();
findCriteria.setFetchSize(1);
findCriteria.setFetchSize(10);
FindControl findControl=new FindControl();
findControl.setRetrieveAllTranslations(true);
System.out.println("before invoking method");
PersonResult personResult=personService.findPerson(findCriteria, findControl);
List<Person> persons=personResult.getValue();
System.out.println("The Response size is ::"+persons.size());
}
#Generated("Oracle JDeveloper")
public static void setPortCredentialProviderList(Map<String, Object> requestContext) throws Exception {
// TODO - Provide the required credential values
String username = "abc";
String password = "acdd";
String clientKeyStore = "";
String clientKeyStorePassword = "";
String clientKeyAlias = "";
String clientKeyPassword = "";
String serverKeyStore = "";
String serverKeyStorePassword = "";
String serverKeyAlias = "";
List<CredentialProvider> credList = new ArrayList<CredentialProvider>();
credList.add(getUNTCredentialProvider(username, password));
credList.add(getBSTCredentialProvider(clientKeyStore, clientKeyStorePassword, clientKeyAlias, clientKeyPassword, serverKeyStore, serverKeyStorePassword, serverKeyAlias, requestContext));
credList.add(getSAMLTrustCredentialProvider());
requestContext.put(WSSecurityContext.CREDENTIAL_PROVIDER_LIST, credList);
}
#Generated("Oracle JDeveloper")
public static CredentialProvider getSAMLTrustCredentialProvider() {
return new SAMLTrustCredentialProvider();
}
#Generated("Oracle JDeveloper")
public static CredentialProvider getUNTCredentialProvider(String username, String password) {
return new ClientUNTCredentialProvider(username.getBytes(), password.getBytes());
}
#Generated("Oracle JDeveloper")
public static CredentialProvider getBSTCredentialProvider(String clientKeyStore, String clientKeyStorePwd,
String clientKeyAlias, String clientKeyPwd,
String serverKeyStore, String serverKeyStorePwd,
String serverKeyAlias,
Map<String, Object> requestContext) throws Exception {
List serverCertList = CertUtils.getCertificate(serverKeyStore, serverKeyStorePwd, serverKeyAlias, "JKS");
List clientCertList = CertUtils.getCertificate(clientKeyStore, clientKeyStorePwd, clientKeyAlias, "JKS");
final X509Certificate serverCert =
(serverCertList != null && serverCertList.size() > 0) ? (X509Certificate) serverCertList.get(0) : null;
final X509Certificate clientCert =
(clientCertList != null && clientCertList.size() > 0) ? (X509Certificate) clientCertList.get(0) : null;
requestContext.put(WSSecurityContext.TRUST_MANAGER, new TrustManager() {
public boolean certificateCallback(X509Certificate[] chain, int validateErr) {
boolean result =
(chain != null && chain.length > 0) && (chain[0].equals(serverCert) || chain[0].equals(clientCert));
return result;
}
});
return new ClientBSTCredentialProvider(clientKeyStore, clientKeyStorePwd, clientKeyAlias, clientKeyPwd, "JKS",
serverCert);
}
}
while running this client stub i am getting following exception.
SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml
(No such file or directory) INFO: Policy subject is not registered.
SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml
(No such file or directory)
SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml
(No such file or directory)
SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml
(No such file or directory)
SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml
(No such file or directory)
INFO: EffectivePolicySetFeature not on the binding,
will look up policy set for; ResourcePattern
[absolutePortableExpression=///UNKNOWN|#MODULE|
WS-Client({http://xmlns.oracle.com/apps/cdm/foundation
/parties/personService/applicationModule/}
PersonService#PersonServiceSoapHttpPort,wls)]
SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml
(No such file or directory)
INFO: EffectivePolicySetFeature=oracle.j2ee.ws.common.wsm
.EffectivePolicySetFeature#76f6c7e1
INFO: WSM Security is not enabled for Policy Subject:
ResourcePattern [absolutePortableExpression=
///UNKNOWN|#MODULE|WS-
Client({http://xmlns.oracle.com/apps/cdm/foundation
/parties/personService/applicationModule/}PersonService
#PersonServiceSoapHttpPort,wls)]
java.lang.SecurityException: keyStoreFilename is either null
or empty string
at weblogic.wsee.security.util.CertUtils.getCertificate
(CertUtils.java:89)
at com.oracle.xmlns.apps.cdm.foundation.parties.personservice
.applicationmodule.PersonServiceSoapHttpPortClient
.getBSTCredentialProvider(PersonServiceSoapHttpPortClient.java:129)
at com.oracle.xmlns.apps.cdm.foundation.parties.personservice
.applicationmodule.PersonServiceSoapHttpPortClient
.setPortCredentialProviderList
(PersonServiceSoapHttpPortClient.java:106)
at com.oracle.xmlns.apps.cdm.foundation.parties.personservice
.applicationmodule.PersonServiceSoapHttpPortClient.main
(PersonServiceSoapHttpPortClient.java:52)
Which version are you runnning? I had the same problem with version 12.1.3 of JDeveloper. Try downloading 12.1.2 from the Oracle website. This did it for me.
Apparently your app requires the JPS library and system picked up the default JPS configuration file, given that the -Doracle.security.jps.config option was not specified. As a result, system is searching ./config/jps-config.xml, which does not exist, at least in that location. Typically, that file should be located at $DOMAIN_HOME/config/fmwconfig.
Ensure your JVM options includes the right JPS config file. This should help at least with this type of error:
SEVERE: java.io.FileNotFoundException: ./config/jps-config.xml (No such file or directory)
Example:
-Doracle.security.jps.config=/dfaut6/otm/product/BIP1117/user_projects/domains/bifoundation_domain/config/fmwconfig/jps-config.xml
Some useful references: http://docs.oracle.com/cd/E25178_01/core.1111/e10043/apjpscfg.htm

How to incorporate Environments with JClouds-Chef API?

I am using JClouds-Chef to:
Bootstrap a newly-provisioned Linux VM; and then
Run the chef-client on that node to configure it
It's important to note that all I'm currently configuring Chef with is a role (that's all it needs; everything else is set up on the Chef server for me):
public class ChefClient {
public configure() {
String vmIp = "myapp01.example.com";
String vmSshUsername = "myuser";
String vmSshPassword = "12345";
String endpoint = "https://mychefserver.example.com";
String client = "myuser";
String validator = "chef-validator";
String clientCredential = Files.toString(new File("C:\\Users\\myuser\\sandbox\\chef\\myuser.pem"), Charsets.UTF_8);
String validatorCredential = Files.toString(new File("C:\\Users\\myuser\\sandbox\\chef\\chef-validator.pem"), Charsets.UTF_8);
Properties props = new Properties();
props.put(ChefProperties.CHEF_VALIDATOR_NAME, validator);
props.put(ChefProperties.CHEF_VALIDATOR_CREDENTIAL, validatorCredential);
props.put(Constants.PROPERTY_RELAX_HOSTNAME, "true");
props.put(Constants.PROPERTY_TRUST_ALL_CERTS, "true");
ChefContext ctx = ContextBuilder.newBuilder("chef")
.endpoint(endpoint)
.credentials(client, clientCredential)
.overrides(props)
.modules(ImmutableSet.of(new SshjSshClientModule())) //
.buildView(ChefContext.class);
ChefService chef = ctx.getChefService();
List<String> runlist = new RunListBuilder().addRole("platformcontrol_dev").build();
ArrayList<String> runList2 = new ArrayList<String>();
for(String item : runlist) {
runList2.add(item);
}
BootstrapConfig bootstrapConfig = BootstrapConfig.builder().runList(runList2).build();
chef.updateBootstrapConfigForGroup("jclouds-chef", bootstrapConfig);
Statement bootstrap = chef.createBootstrapScriptForGroup("jclouds-chef");
SshClient.Factory sshFactory = ctx.unwrap().utils()
.injector().getInstance(Key.get(new TypeLiteral<SshClient.Factory>() {}));
SshClient ssh = sshFactory.create(HostAndPort.fromParts(vmIp, 22),
LoginCredentials.builder().user(vmSshUsername).password(vmSshPassword).build());
ssh.connect();
try {
StringBuilder rawScript = new StringBuilder();
Map<String, String> resolvedFunctions = ScriptBuilder.resolveFunctionDependenciesForStatements(
new HashMap<String, String>(), ImmutableSet.of(bootstrap), OsFamily.UNIX);
ScriptBuilder.writeFunctions(resolvedFunctions, OsFamily.UNIX, rawScript);
rawScript.append(bootstrap.render(OsFamily.UNIX));
ssh.put("/tmp/chef-bootstrap.sh", rawScript.toString());
ExecResponse result = ssh.exec("bash /tmp/chef-bootstrap.sh");
} catch(Throwable t) {
println "Exception: " + t.message
} finally {
ssh.disconnect();
}
}
}
Our in-house "Chef" (our devops guy) now wants to add the concept of Chef "environments" to all our recipes in addition to the existing roles. This is so that we can specify environment-specific roles for each node. My question: does the JClouds-Chef API handle environments? If so, how might I modify the code to incorporate environment-specific roles?
Is it just as simple as:
BootstrapConfig bootstrapConfig = BootstrapConfig.builder()
.environment("name-of-env-here?").runList(runList2).build();
Yes, it is that simple. That will tell the bootstrap script to register the node in the specified environment.
Take into account, though, that the environment must already exist in the Chef Server. If you want to create nodes in new environments, you can also create them programmatically as follows:
ChefApi api = ctx.unwrapApi(ChefApi.class);
if (api.getEnvironment("environment-name") == null) {
Environment env = Environment.builder()
.name("environment-name")
.description("Some description")
.build();
api.createEnvironment(env);
}

Shiro LDAP Authorization config

Could you please help me with the following situation?
Background information:
I'm using the Vaadin framework.
I'm using the Java security framework Shiro
I'm using ssl.
Authentication works.
Username syntax = pietj#.lcl , jank#.lcl
memberOf field is being used as role.
shiro.ini
[main]
contextFactory = org.apache.shiro.realm.ldap.JndiLdapContextFactory
contextFactory.url = ldaps://<SERVER>:636
contextFactory.systemUsername = <USERNAME>#<COMPANY>
contextFactory.systemPassword = <PASSWORD>
contextFactory.environment[java.naming.security.protocol] = ssl
realm = org.apache.shiro.realm.activedirectory.ActiveDirectoryRealm
realm.ldapContextFactory = $contextFactory
realm.searchBase = "OU=<APPDIR>,DC=<COMPANY>,DC=lcl"
realm.groupRolesMap = "CN=<ROLE>,OU=<APPDIR>,DC=<COMPANY>,DC=lcl":"Admin"
[roles]
# 'Admin' role has permissions *
Admin = *
Goal
Authorization mapping based on the memberOf field from the currentUser.
Problem
currentUser.hasRole("Admin") always return false.
Questions
Is the above shiro.ini correct?
How do I fix the problem?
I ran into a similar issue using Shiro 1.2.4. Your Shiro configuration is probably OK and the problem lies in ActiveDirectory configuration.
In my setup some users had the userPrincipalName attribute set, while other users hadn't. You can check your in AD server with Sysinternals Active Directory Explorer for example.
This attribute is the one used by Shiro to search for a particular user, then it looks for groups defined in the memberOf attribute.
Take a look at ActiveDirectoryRealm.java source code, method Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) the exact query used is
String searchFilter = "(&(objectClass=*)(userPrincipalName={0}))";
So you have two solutions:
Set userPrincipalName attribute on every user
Change how Shiro searches for users
I went for the second solution. Changing the search query is harder than it should be: you have to customize queryForAuthorizationInfo and getRoleNamesForUser (because its private) methods of ActiveDirectoryRealm class. This is how I did it:
public class CustomActiveDirectoryRealm extends ActiveDirectoryRealm {
#Override
protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals, LdapContextFactory ldapContextFactory) throws NamingException {
String username = (String) getAvailablePrincipal(principals);
// Perform context search
LdapContext ldapContext = ldapContextFactory.getSystemLdapContext();
Set<String> roleNames = null;
try {
roleNames = getRoleNamesForUser(username, ldapContext);
} finally {
LdapUtils.closeContext(ldapContext);
}
return buildAuthorizationInfo(roleNames);
}
// Customize your search query here
private static final String USER_SEARCH_FILTER = "(&(objectClass=*)(sn={0}))";
private Set<String> getRoleNamesForUser(String username, LdapContext ldapContext) throws NamingException {
Set<String> roleNames;
roleNames = new LinkedHashSet<String>();
SearchControls searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String userPrincipalName = username.replace("acegas\\", "");
if (principalSuffix != null) {
userPrincipalName += principalSuffix;
}
Object[] searchArguments = new Object[]{userPrincipalName};
NamingEnumeration answer = ldapContext.search(searchBase, USER_SEARCH_FILTER, searchArguments, searchCtls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
Attributes attrs = sr.getAttributes();
if (attrs != null) {
NamingEnumeration ae = attrs.getAll();
while (ae.hasMore()) {
Attribute attr = (Attribute) ae.next();
if (attr.getID().equals("memberOf")) {
Collection<String> groupNames = LdapUtils.getAllAttributeValues(attr);
Collection<String> rolesForGroups = getRoleNamesForGroups(groupNames);
roleNames.addAll(rolesForGroups);
}
}
}
}
return roleNames;
}
}
And then of course use this class as Realm in shiro.ini
[main]
realm = your.package.CustomActiveDirectoryRealm
realm.ldapContextFactory = $contextFactory
realm.searchBase = "OU=<APPDIR>,DC=<COMPANY>,DC=lcl"
realm.groupRolesMap = "CN=<ROLE>,OU=<APPDIR>,DC=<COMPANY>,DC=lcl":"Admin"

Jacob and wireless

I am using Jacob to find out the MAC addresses of all access points that are detected by my wireless NIC.
According to WMI documentation Ndis80211BSSIList is: "The list of in-range BSSIDs and their properties". As far as I can understand it returns an array of objects of the Class MSNdis_80211_WLanBssId, that each of them has some properties.
My question is how I can access these properties of each of these instances (each instance is a different BSSID with properties such as MAC Address or SSID). Any help would be valuable.
public class testWMIJacob {
public static void main(String[] args) {
String host = "localhost";
String connectStr = String.format("winmgmts:\\\\%s\\root\\wmi", host);
String query = "SELECT * FROM MSNdis_80211_BSSIList ";
ActiveXComponent axWMI = new ActiveXComponent(connectStr);
Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));
EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
Dispatch item = null;
while (enumVariant.hasMoreElements()) {
item = enumVariant.nextElement().toDispatch();
String req = Dispatch.call(item,"Ndis80211BSSIList").toString();
}
}
}

How to obtain a kerberos service ticket via GSS-API?

Does anyone know how to get a service ticket from the Key Distribution Center (KDC) using the Java GSS-API?
I have a thick-client-application that first authenticates via JAAS using the Krb5LoginModule to fetch the TGT from the ticket cache (background: Windows e.g. uses a kerberos implementation and stores the ticket granting ticket in a secure memory area). From the LoginManager I get the Subject object which contains the TGT. Now I hoped when I create a specific GSSCredential object for my service, the service ticket will be put into the Subject's private credentials as well (I've read so somewhere in the web). So I have tried the following:
// Exception handling ommitted
LoginContext lc = new LoginContext("HelloEjbClient", new DialogCallbackHandler());
lc.login()
Subject.doAs(lc.getSubject(), new PrivilegedAction() {
public Object run() {
GSSManager manager = GSSManager.getInstance();
GSSName clientName = manager.createName("clientUser", GSSName.NT_USER_NAME);
GSSCredential clientCreds = manager.createCredential(clientName, 8 * 3600, createKerberosOid(), GSSCredential.INITIATE_ONLY);
GSSName serverName = manager.createName("myService#localhost", GSSName.NT_HOSTBASED_SERVICE);
manager.createCredential(serverName, GSSCredential.INDEFINITE_LIFETIME, createKerberosOid(), GSSCredential.INITIATE_ONLY);
return null;
}
private Oid createKerberosOid() {
return new Oid("1.2.840.113554.1.2.2");
}
});
Unfortunately I get a GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt).
My understanding of getting the service ticket was wrong. I do not need to get the credentials from the service - this is not possible on the client, because the client really doesn't have a TGT for the server and therefore doesn't have the rights to get the service credentials.
What's just missing here is to create a new GSSContext and to initialize it. The return value from this method contains the service ticket, if I have understood that correctly. Here is a working code example. It must be run in a PrivilegedAction on behalf of a logged in subject:
GSSManager manager = GSSManager.getInstance();
GSSName clientName = manager.createName("clientUser", GSSName.NT_USER_NAME);
GSSCredential clientCred = manager.createCredential(clientName,
8 * 3600,
createKerberosOid(),
GSSCredential.INITIATE_ONLY);
GSSName serverName = manager.createName("http#server", GSSName.NT_HOSTBASED_SERVICE);
GSSContext context = manager.createContext(serverName,
createKerberosOid(),
clientCred,
GSSContext.DEFAULT_LIFETIME);
context.requestMutualAuth(true);
context.requestConf(false);
context.requestInteg(true);
byte[] outToken = context.initSecContext(new byte[0], 0, 0);
System.out.println(new BASE64Encoder().encode(outToken));
context.dispose();
The outToken contains then contains the Service Ticket. However this is not the way the GSS-API was meant to be used. Its goal was to hide those details to the code, so it is better to establish a GSSContext using the GSS-API on both sides. Otherwise you really should know what you are doing because of potential security holes.
For more information read the Sun SSO tutorial with kerberos more carefully than I did.
EDIT:
Just forgot that I am using Windows XP with SP2. There is a new "feature" in this version of Windows that disallows using the TGT in the Windows RAM. You have to edit the registry to allow this. For more information have a look at the JGSS Troubleshooting page topic in case you experience a "KrbException: KDC has no support for encryption type (14)" like I did.
I had a lot of problems to use this code, but I have at least a solution. I post it here, perhaps it will help some of you...
/**
* Tool to retrieve a kerberos ticket. This one will not be stored in the windows ticket cache.
*/
public final class KerberosTicketRetriever
{
private final static Oid KERB_V5_OID;
private final static Oid KRB5_PRINCIPAL_NAME_OID;
static {
try
{
KERB_V5_OID = new Oid("1.2.840.113554.1.2.2");
KRB5_PRINCIPAL_NAME_OID = new Oid("1.2.840.113554.1.2.2.1");
} catch (final GSSException ex)
{
throw new Error(ex);
}
}
/**
* Not to be instanciated
*/
private KerberosTicketRetriever() {};
/**
*
*/
private static class TicketCreatorAction implements PrivilegedAction
{
final String userPrincipal;
final String applicationPrincipal;
private StringBuffer outputBuffer;
/**
*
* #param userPrincipal p.ex. <tt>MuelleHA#MYFIRM.COM</tt>
* #param applicationPrincipal p.ex. <tt>HTTP/webserver.myfirm.com</tt>
*/
private TicketCreatorAction(final String userPrincipal, final String applicationPrincipal)
{
this.userPrincipal = userPrincipal;
this.applicationPrincipal = applicationPrincipal;
}
private void setOutputBuffer(final StringBuffer newOutputBuffer)
{
outputBuffer = newOutputBuffer;
}
/**
* Only calls {#link #createTicket()}
* #return <tt>null</tt>
*/
public Object run()
{
try
{
createTicket();
}
catch (final GSSException ex)
{
throw new Error(ex);
}
return null;
}
/**
*
* #throws GSSException
*/
private void createTicket () throws GSSException
{
final GSSManager manager = GSSManager.getInstance();
final GSSName clientName = manager.createName(userPrincipal, KRB5_PRINCIPAL_NAME_OID);
final GSSCredential clientCred = manager.createCredential(clientName,
8 * 3600,
KERB_V5_OID,
GSSCredential.INITIATE_ONLY);
final GSSName serverName = manager.createName(applicationPrincipal, KRB5_PRINCIPAL_NAME_OID);
final GSSContext context = manager.createContext(serverName,
KERB_V5_OID,
clientCred,
GSSContext.DEFAULT_LIFETIME);
context.requestMutualAuth(true);
context.requestConf(false);
context.requestInteg(true);
final byte[] outToken = context.initSecContext(new byte[0], 0, 0);
if (outputBuffer !=null)
{
outputBuffer.append(String.format("Src Name: %s\n", context.getSrcName()));
outputBuffer.append(String.format("Target : %s\n", context.getTargName()));
outputBuffer.append(new BASE64Encoder().encode(outToken));
outputBuffer.append("\n");
}
context.dispose();
}
}
/**
*
* #param realm p.ex. <tt>MYFIRM.COM</tt>
* #param kdc p.ex. <tt>kerbserver.myfirm.com</tt>
* #param applicationPrincipal cf. {#link #TicketCreatorAction(String, String)}
* #throws GSSException
* #throws LoginException
*/
static public String retrieveTicket(
final String realm,
final String kdc,
final String applicationPrincipal)
throws GSSException, LoginException
{
// create the jass-config-file
final File jaasConfFile;
try
{
jaasConfFile = File.createTempFile("jaas.conf", null);
final PrintStream bos = new PrintStream(new FileOutputStream(jaasConfFile));
bos.print(String.format(
"Krb5LoginContext { com.sun.security.auth.module.Krb5LoginModule required refreshKrb5Config=true useTicketCache=true debug=true ; };"
));
bos.close();
jaasConfFile.deleteOnExit();
}
catch (final IOException ex)
{
throw new IOError(ex);
}
// set the properties
System.setProperty("java.security.krb5.realm", realm);
System.setProperty("java.security.krb5.kdc", kdc);
System.setProperty("java.security.auth.login.config",jaasConfFile.getAbsolutePath());
// get the Subject(), i.e. the current user under Windows
final Subject subject = new Subject();
final LoginContext lc = new LoginContext("Krb5LoginContext", subject, new DialogCallbackHandler());
lc.login();
// extract our principal
final Set<Principal> principalSet = subject.getPrincipals();
if (principalSet.size() != 1)
throw new AssertionError("No or several principals: " + principalSet);
final Principal userPrincipal = principalSet.iterator().next();
// now try to execute the SampleAction as the authenticated Subject
// action.run() without doAsPrivileged leads to
// No valid credentials provided (Mechanism level: Failed to find any Kerberos tgt)
final TicketCreatorAction action = new TicketCreatorAction(userPrincipal.getName(), applicationPrincipal);
final StringBuffer outputBuffer = new StringBuffer();
action.setOutputBuffer(outputBuffer);
Subject.doAsPrivileged(lc.getSubject(), action, null);
return outputBuffer.toString();
}
public static void main (final String args[]) throws Throwable
{
final String ticket = retrieveTicket("MYFIRM.COM", "kerbserver", "HTTP/webserver.myfirm.com");
System.out.println(ticket);
}
}

Categories