How do you preform an EJB lookup with application security? - java

I'm trying to lookup an EJB from a standalone java application. I'm thinking in terms of WebSphere Application Server 6.1, but if someone knows how to do this for another application server, it may get me in the right direction.
What I'm currently doing:
initialContext= new InitialContext(env);
initialContext.lookup("");
lc = new LoginContext("WSLogin", new WSCallbackHandlerImpl("wasadmin", "defaultWIMFileBasedRealm", "wasadmin"));
lc.login();
subject = lc.getSubject();
WSSubject.setRunAsSubject(subject);
This isn't working... my subject is still "/UNAUTHENTICATED", and I get an error when I try to lookup the EJB. I'm also specifying the following parameters to the VM when executing the application:
-Dcom.ibm.CORBA.ConfigURL="C:\was\profiles\AppSrv01\properties\sas.client.props"
-Djava.security.auth.login.config="C:\was\profiles\AppSrv01\properties\wsjaas_client.conf"

For WebSphere 6, was trying to acceess an secured EJB from a servlet (Jersey-RESTful WAR) also deployed in the same WebSphere; Here is the code that works
Properties prop = new Properties();
prop.put("org.omg.CORBA.ORBClass", "com.ibm.CORBA.iiop.ORB");
prop.put("java.naming.factory.initial", "com.ibm.websphere.naming.WsnInitialContextFactory");
prop.put("java.naming.provider.url", "corbaloc:iiop:localhost:9810");
prop.put("com.ibm.CORBA.securityEnabled", "true");
prop.put("com.ibm.CORBA.validateBasicAuth", "true");
Context ctx;
try {
ctx = new InitialContext(prop);
System.out.println("Resolved Inital Context");
Object ejbHome = ctx.lookup("");
System.out.println("Resolved Home OperationManagerEJB");
logger.info("So far so good, tryining to Login ");
LoginContext lc;
lc = new LoginContext("WSLogin",new WSCallbackHandlerImpl("username","password"));
lc.login();
logger.info("Login Suceeded with omc_user");
WSSubject.setRunAsSubject(lc.getSubject()); //This is one key call
logger.info("Setting the authorization sibject");
References
http://pic.dhe.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=%2Fcom.ibm.websphere.express.doc%2Finfo%2Fexp%2Fae%2Frtrb_secprobs.html
http://pic.dhe.ibm.com/infocenter/wasinfo/v6r0/index.jsp?topic=%2Fcom.ibm.websphere.express.doc%2Finfo%2Fexp%2Fae%2Fxsec_jaas.html
http://pic.dhe.ibm.com/infocenter/wasinfo/v6r0/index.jsp?topic=%2Fcom.ibm.websphere.express.doc%2Finfo%2Fexp%2Fae%2Fxsec_jaas.html

Related

Using datasource connection of weblogic server

I have wrote Java Client application (bean for Oracle form) to access the data through "jdbcdatasource" created on Weblogic 12c. It works fine when I am running on desktop, but when I am embedding on oracle forms as a bean, it gives following error:
java.lang.ClassNotFoundException: weblogic.jdbc.common.internal.RmiDataSource_12210_WLStub
java bean is an executable jar file includes all the dependency jar file, and it is executed independently by double click.
Here is a code:
Context ctx = null;
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3:" + url + ":7001");
if(sUser != null && sPwd != null){
ht.put(Context.SECURITY_PRINCIPAL, sUser);
ht.put(Context.SECURITY_CREDENTIALS, sPwd);
}
ctx = new InitialContext(ht);
System.out.println("!!! WebLogic Server Connection Done!");
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("myDatasource");
java.sql.Connection conn = ds.getConnection();
System.out.println("!!! DataSource Connection Done!");
In the environment of Oracle forms it connect to the weblogic server but could not access the data source by displaying above error.
Any suggestion?
Just to make things clear to me.
When you say :
"to access the data through "jdbcdatasource" created on Weblogic 12c."
and you code shows:
"javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("myDatasource");"
The lookup parameter value shouldn't be exactly like "jdbcdatasource" instead of "myDataSource' as you stated before or it was just to explain your situation ?

Jetty: programmatically authentication not working after reboot

I am new to Jetty and working on a test app to do the basic authentication. There is no web.xml in the project. Everything is handled by code.
I followed this example:https://github.com/eclipse/jetty.project/blob/master/examples/embedded/src/main/java/org/eclipse/jetty/embedded/SecuredHelloHandler.java
Here is the test code
Server server = new Server(8080);
LoginService loginService = new HashLoginService("MyRealm", path);
loginService.setRefreshInterval(5);
server.addBean(loginService);
ConstraintSecurityHandler security = new ConstraintSecurityHandler();
server.setHandler(security);
Constraint constraint = new Constraint();
constraint.setName("auth");
constraint.setAuthenticate(true);
constraint.setRoles(new String[] { "user", "admin" });
ConstraintMapping mapping = new ConstraintMapping();
mapping.setPathSpec("/*");
mapping.setConstraint(constraint);
security.setConstraintMappings(Collections.singletonList(mapping));
security.setAuthenticator(new BasicAuthenticator());
security.setLoginService(loginService);
HelloWorld hw = new HelloWorld();
security.setHandler(hw);
server.start();
Here is my test realm.properties
guest:CRYPT:guVeRgi5kAY4k,user,admin
The code is triggered by a test button in a test PDE project. When the server started for the first time, it prompted a window for username/password. I typed "guest" and "guest", and it worked. But after that, when I restarted the server, it never asked for username/password again. The page was loaded without authentication. If I changed password in the realm property file, the prompt will show up again, and still only for that one time. What did I miss? Thanks
Standard HTTP Cookie and Servlet Session behavior is what is going on.
The restart of the server doesn't cause the client provided Cookies to no longer work. You'll want to configure your Cookie and Session behavior to suit your needs (search on SessionCookieConfig and its ilk).

ldap connection pool in web application

I need to use ldap connection pooling in a web application. To authenticate admin, I am using below code:
Properties props = new Properties();
System.setProperty("com.sun.jndi.ldap.connect.pool", "true");
System.setProperty("com.sun.jndi.ldap.connect.pool.maxsize", "1");
System.setProperty("com.sun.jndi.ldap.connect.pool.debug", "fine");
props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
props.put(Context.PROVIDER_URL, "ldap://localhost:10389/o=myldap");
props.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");//adminuser
props.put(Context.SECURITY_CREDENTIALS, "xxxxx");
InitialDirContext context = new InitialDirContext(props);
To lookup and authenticate another user, I need to change the SECURITY_PRINCIPAL and SECURITY_CREDENTIALS and then create a new context again. When I do this is a POJO, it uses connection pool but when I use this in multi user web application (I tried it with two threads), it does not use connection pool.
What workaround can be used for this?
You need to set the parameters as JVM system parameters, using -D parameters on the java invocation.
System.setProperty("com.sun.jndi.ldap.connect.pool", "true");
System.setProperty("com.sun.jndi.ldap.connect.pool.maxsize", "1");
System.setProperty("com.sun.jndi.ldap.connect.pool.debug", "fine");
Wrong properties object. You should be setting those into the 'props' object, not the system properties object.
EDIT And don't debug to true. Setting it has has the curious effect of turning pooling off.

How to invalidate selected session programmatically?

I'm trying to invalidate selected session (with given sessionId) from my web application runing on Jboss 4.2. Everything works perfect from JMX console but
I don't know how to do the same in java code. Here is what i have already created:
MBeanServer server=MBeanServerLocator.locateJBoss();
ObjectName objectName = new ObjectName("jboss.web:host=localhost,path=/,type=Manager");
ManagerBase manager = (ManagerBase)MBeanServerInvocationHandler.newProxyInstance(server, objectName, Manager.class, false);
manager.expireSession("sessionID");
But this code gives this exception:
Caused by: java.lang.ClassCastException: com.sun.proxy.$Proxy574 cannot be cast to org.apache.catalina.session.ManagerBase
Can You help me?
You have to collect the session in a map check following link :
How can i load Java HttpSession from JSESSIONID?
Find number of active sessions created from a given client IP
How to easily implement "who is online" in Grails or Java Application?
If you are still looking for the answer. That snippet works for me:
MBeanServer server = java.lang.management.ManagementFactory.getPlatformMBeanServer();
ObjectName objectName=new ObjectName("jboss.web:type=Manager,path=/test,host=default-host");
// declare signature of the parameter
String[] sig = { "java.lang.String"};
// your session id e.g. A7rOCAlFa+9uCeUfYNjJpd3r.undefined
Object[] opArgs1 = { sessionID };
// call the method
String value = (String) server.invoke(objectName, "expireSession",
opArgs1, sig);
I am working on JBoss-7.1.1.Final. My application is called "test", hence the context root "/test". You should create objectName with name of your application.

Can't edit static assets while application is running

While my application is running, I'm not able to save static assets that are being served. This is kind of a pain for debugging as I'd like to just be able to refresh the page when editing css, js and html.
I thought that the line listener.getFileCache().setEnabled(false); below would do the trick, but it still won't let me edit these files. Is there something else I missed in the configuration?
Here's my application...
final HttpServer server = HttpServer.createSimpleServer(".", 8181);
WebappContext ctx = new WebappContext("Socket", "/");
//enable annotation configuration
ctx.addContextInitParameter("contextClass", "org.springframework.web.context.support.AnnotationConfigWebApplicationContext");
ctx.addContextInitParameter("contextConfigLocation", "com.production");
//allow spring to do all of it's stuff
ctx.addListener("org.springframework.web.context.ContextLoaderListener");
//enable web socket support
final WebSocketAddOn addon = new WebSocketAddOn();
for (NetworkListener listener : server.getListeners()) {
listener.registerAddOn(addon);
//if false, local files (html, etc.) can be modified without restarting the server
listener.getFileCache().setEnabled(false);
}
//add jersey servlet support
//#todo add spring support to jersey
ServletRegistration jerseyServletRegistration = ctx.addServlet("JerseyServlet", new ServletContainer());
jerseyServletRegistration.setInitParameter("com.sun.jersey.config.property.packages", "com.production.resource");
jerseyServletRegistration.setLoadOnStartup(1);
jerseyServletRegistration.addMapping("/api/*");
//add atmosphere servlet support
AtmosphereServlet atmosphereServlet = new AtmosphereServlet();
AtmosphereFramework f = atmosphereServlet.framework();
ReflectorServletProcessor r = new ReflectorServletProcessor();
r.setServletClassName("com.sun.jersey.spi.spring.container.servlet.SpringServlet");
f.addAtmosphereHandler("/socket/*", r);
ServletRegistration atmosphereServletRegistration = ctx.addServlet("AtmosphereServlet", atmosphereServlet);
atmosphereServletRegistration.setInitParameter("org.atmosphere.websocket.messageContentType", "application/json");
atmosphereServletRegistration.setInitParameter("com.sun.jersey.config.property.packages", "com.production.resource");
atmosphereServletRegistration.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature", "true");
//atmosphereServletRegistration.addMapping("/socket/*");
atmosphereServletRegistration.setLoadOnStartup(1);
//serve static assets
StaticHttpHandler staticHttpHandler = new StaticHttpHandler("src/main/web");
server.getServerConfiguration().addHttpHandler(staticHttpHandler, "/");
Update:
I ended up migrating my AngularJS application outside of the java world due to the nature of AngularJS not needing to be a part of the java project.

Categories

Resources