mBeans Client deployed on weblogic gives a security exception? - security

iam trying to follow the documentation of the mbeans for weblogic and create a web application
to access an already created custom beans running in another application deployed in the server .
iam using this code
InitialContext ctx = new InitialContext();
MBeanServer server = (MBeanServer)ctx.lookup("java:comp/env/jmx/runtime");
String serverName = System.getProperty("weblogic.Name");
ObjectName on =new ObjectName("com.myCompanyName:Name=MyCutomBean,Type=MyCutomBean");
boolean boolresult=(Boolean)server.invoke(on, "myMethod",
new Object[]{"a","b","c"}
,new String[]{"java.lang.String","java.lang.String","java.lang.String"}); //throw exception
out.print(result);
out.print(boolresult);
when i try to access our custom beans i got this exception :
Access not allowed for subject: principals=[], on ResourceType: Name Action: execute, Target: myMethod
what could be the problem ?

i finally find a solution
to avoid this exception u need to authenticate your Context using the following :
Hashtable props = new Hashtable();
props.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
props.put(Context.SECURITY_PRINCIPAL, "<userName>");
props.put(Context.SECURITY_CREDENTIALS, "<password>");
Context ctx = new InitialContext(props); MBeanServer server = (MBeanServer)ctx.lookup("java:comp/env/jmx/runtime");
Hope this will help someone

Related

How to get current caller/principal in JMX mbean?

I have one case which works on JBoss 4.2.
Client login (with JAAS, ClientLoginModule)
Client get JMX connection from JBoss JMX server
Client call mbean API;
Server will check current caller/principal is, whether he/she has the enough privilege to do the action.
Now with Wildfly 9, we do the similar thing, moreover, we have set the username/password when getting JMX connection.
// urlString likes:service:jmx:remote://localhost:9999
JMXServiceURL serviceURL = new JMXServiceURL(urlString);
Map<String, Object> env = new HashMap<String, Object>();
String[] creds = new String[2];
creds[0] = username_;
creds[1] = password_;
env.put(JMXConnector.CREDENTIALS, creds);
JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL, env);
MBeanServerConnection connection = jmxConnector.getMBeanServerConnection();
However, at step3, JMX server find current caller/principal is null.
Do you know why? Or how to resolve this.
Are there any interceptors for JMX just like EJB?

No LoginModules configured for DefaultPrincipalMapping WAS Libert y profile 8.5.5.9

I used the info in this link https://www.ibm.com/support/knowledgecenter/SSEQTP_8.5.5/com.ibm.websphere.wlp.doc/ae/twlp_dev_prog_login_auth_data.html As per my info which I got from this discussion thread. https://developer.ibm.com/answers/questions/261209/websphere-liberty-profile-and-j2c-authdata-retriev-1.html
The DefaultPrincipalMapping programmatic login is avaiable and should work. I configured everything updated to Liberty profile v 8.5.5.9 , yet my code throws exception at [err] javax.security.auth.login.LoginException: No LoginModules configured for DefaultPrincipalMapping [err] at javax.security.auth.login.LoginContext.init(LoginContext.java:264) [err] at javax.security.auth.login.LoginContext.(LoginContext.java:417) Here is my code snippet..
Context context = new InitialContext();
String user = (String) context.lookup("cell/persistent/ADBindUser");
String password = (String) context.lookup("cell/persistent/ADBindPwd");
Map<String, String> map = new HashMap<String, String>();
map.put(Constants.MAPPING_ALIAS, "WPSBIND");
// CallbackHandler callbackHandler = // WSMappingCallbackHandlerFactory.getInstance().getCallbackHandler(map, null);
CallbackHandler callbackHandler =new WSMappingCallbackHandler(map, null);
LoginContext loginContext =
new LoginContext("DefaultPrincipalMapping", callbackHandler);
try{
loginContext.login();
}catch(LoginException le) {
}
Can any one please tell me what I am missing here.
Instead of "DefaultPrincipalMapping" the login configuration "system.DEFAULT" did the job for me.
The final hint was hidden in the documentation:
system.DEFAULT
Used for login when no JAAS configuration is specified.
...
The system.WEB_INBOUND and system.DEFAULT configurations have these
default login modules in this order: hashtable, userNameAndPassword,
certificate, and token. The WSLogin configuration has the proxy login module
as the default login module, and the proxy delegates all the
operations to the real login module in system.DEFAULT.
WSLogin fails with an Unrecognized Callback in case the application uses e.g. org.jboss.security.auth.callback.UsernamePasswordHandler as the callback. If the application cannot be modified, system.DEFAULT provides an alternative.

Call Web Service via crm workflow

Currently i'm working on a crm project. In this project i have to send data to web service and take refined data back. This operation must be work on custom workflow but i'm stuck infact i have no idea how to do it? Any suggestions?
Here is my service code;
var tmpIncident = getIncidentById(organizationServiceContext);
if (tmpIncident != null) //if we have decent incident we connect service and proceed the data.
{
GetCustomerInfoService.TransactionServiceClient client = new GetCustomerInfoService.TransactionServiceClient();
GetCustomerInfoService.TransactionRequest request = new GetCustomerInfoService.TransactionRequest();
#region authentication
request.AuthenticationData.UserName = "user";
request.AuthenticationData.Password = "pass";
#endregion
Guid id = Guid.NewGuid(); //create random guid
request.RequestId = id.ToString();
request.OrderNumber = tmpIncident.vrp_ordernumber;
GetCustomerInfoService.TransactionResponse response = client.GetTransactionByOrderNumber(request);
tmpIncident.CustomerId = new EntityReference("Contact", new Guid(response.Message));
this.updateChanges(organizationServiceContext, tmpIncident);
client.Close();
}
When i tested plugin, i received that error;
Error Message:
Unhandled Exception: System.InvalidOperationException: Could not find default endpoint element that references contract 'GetCustomerInfoService.ITransactionService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.
at System.ServiceModel.Description.ConfigLoader.LoadChannelBehaviors(ServiceEndpoint serviceEndpoint, String configurationName)
at System.ServiceModel.ChannelFactory.InitializeEndpoint(String configurationName, EndpointAddress address)
at System.ServiceModel.ChannelFactory1..ctor(String endpointConfigurationName, EndpointAddress remoteAddress)
at System.ServiceModel.ConfigurationEndpointTrait1.CreateSimplexFactory()
at System.ServiceModel.ClientBase1.CreateChannelFactoryRef(EndpointTrait1 endpointTrait)
at System.ServiceModel.ClientBase`1.InitializeChannelFactoryRef()
at Vrp.Crm.PluginLibrary2013.GetCustomerInfoService.TransactionServiceClient..ctor() in :line 0
at Vrp.Crm.PluginLibrary2013.CustomWorkflows.SetCumstomerIdToIncident.Execute(CodeActivityContext context) in c:\Veripark\Projects\gisik\DRCRM.VERITOUCH.CRM2013\PluginLibrary2013\CustomWorkflows\CheckSubIncidentForMainIncident.cs:line 72
at System.Activities.CodeActivity.InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
at System.Activities.Runtime.ActivityExecutor.ExecuteActivityWorkItem.ExecuteBody(ActivityExecutor executor, BookmarkManager bookmarkManager, Location resultLocation)
Assuming that you are using Dynamics CRM. This is a high-level overview:
Create a custom workflow activity that makes the actual call to the webservice. This should help you get started: https://msdn.microsoft.com/en-us/library/gg328515.aspx
The custom activity would have output parameters that would return the results from the webservice back to the calling CRM workflow.
Finally create the workflow and its triggers that would make use of your custom activity. More info:
http://crmbook.powerobjects.com/system-administration/processes/workflows/
https://msdn.microsoft.com/en-us/library/gg328264.aspx
I hope this is enough information to get you heading down the right path.

simple GlassFish embedded security fails: Login failed: Unable to locate a login configuration

I'm creating unit tests for our application, and I'm stuck. For testing I have a simple HelloWebServlet that I'm protecting via annotations:
#WebServlet(urlPatterns = {"/hello"})
#ServletSecurity(#HttpConstraint(rolesAllowed = {"user"}))
I'm starting the server the way that's always worked OK (see [1]) and creating users (see [2]) seems to be OK because output from CommandRunner calls to list-file-users and list-file-groups are correct, but I'm getting this error when I try to connect using the username and password:
WARNING: WEB9102: Web Login Failed: com.sun.enterprise.security.auth.login.common.LoginException: Login failed: Unable to locate a login configuration
The calling code uses the Jersey client API:
#Test
public void testPingServletLoggedIn() {
Client client = Client.create();
client.addFilter(new HTTPBasicAuthFilter(GlassFishServerHelper.USERNAME, "xx"));
WebResource webResource = client.resource(GlassFishServerHelper.getBaseUri() + "/hello");
ClientResponse clientResponse = webResource
.accept(MediaType.TEXT_PLAIN)
.get(ClientResponse.class); // #GET
assertEquals(ClientResponse.Status.OK, clientResponse.getClientResponseStatus());
}
(Note: I tried to set javax.enterprise.system.core.security.level=FINE but that call failed with: PlainTextActionReporterFAILURENo configuration found for javax.enterprise.system.core.security . Drat!)
I've tried this against both glassfish-embedded-all-3.1.2.jar (our production version) and glassfish-embedded-all-3.2-b06.jar with the same results. What do you think would solve this? I've struggled and succeeded way too many times with GFE to give up without a fight!
==== [1] server startup (excerpt) ====
public static void startServer() {
GlassFishProperties gfProps = new GlassFishProperties();
gfProps.setPort("http-listener", PORT);
GLASSFISH = GlassFishRuntime.bootstrap().newGlassFish(gfProps);
GLASSFISH.start();
enableDefaultPrincipleToRoleMapping();
createUsersAndGroups();
ScatteredArchive archive = new ScatteredArchive(WEB_APP_NAME, ScatteredArchive.Type.WAR);
File classesDir = new File("out/production/simple-security-servlet-test");
archive.addClassPath(classesDir);
DEPLOYER = GLASSFISH.getDeployer();
APP_NAME = DEPLOYER.deploy(archive.toURI());
private static void enableDefaultPrincipleToRoleMapping() throws GlassFishException {
CommandRunner cr = GLASSFISH.getCommandRunner();
CommandResult result = cr.run("set",
"server-config.security-service.activate-default-principal-to-role-mapping=true");
}
==== [2] user creation (excerpt) ====
private static void createUsersAndGroups() throws GlassFishException {
CommandRunner commandRunner = GLASSFISH.getCommandRunner();
File passwordFile = new File("password-file.txt");
CommandResult result = commandRunner.run("create-file-user",
"--passwordfile", passwordFile.getAbsolutePath(),
"--groups", "user",
USERNAME
);
}
I was getting the same error and have managed to work around it, although my situation is slightly different. I'm starting GF 3.1.2 from the "maven-embedded-glassfish-plugin" maven plugin, but this might work for you as well.
Try setting the following system property:
java.security.auth.login.config=target/test-classes/login.conf
This should point to a copy of the login.conf file. You can find this file in the "config" folder in any Glassfish domain folder.

SharePoint 2010 Client Object Model - Kerberos/Claims Authentication

I'm trying to read a value from a list in a remote SharePoint site (different SP Web App). The web apps are set up with Claims Auth, and the client web app SP Managed account is configured with an SPN. I believe Kerberos and claims are set up correctly, but I am unable to reach the remote server, and the request causes an exception: "The remote server returned an error: (401) Unauthorized."
The exception occurs in the line ctx.ExecuteQuery(); but it does not catch the exception in the if (scope.HasException) instead, the exception is caught by the calling code (outside of the using{} block).
When I look at the traffic at the remote server using Wireshark, it doesn't look like the request is even getting to the server; it's almost as if the 401 occurs before the Kerberos ticket is exchanged for the claim.
Here's my code:
using (ClientContext ctx = new ClientContext(contextUrl))
{
CredentialCache cc = new CredentialCache();
cc.Add(new Uri(contextUrl), "Kerberos", CredentialCache.DefaultNetworkCredentials);
ctx.Credentials = cc;
ctx.AuthenticationMode = ClientAuthenticationMode.Default;
ExceptionHandlingScope scope = new ExceptionHandlingScope(ctx);
Web ctxWeb = ctx.Web;
List ctxList;
Microsoft.SharePoint.Client.ListItemCollection listItems;
using (scope.StartScope())
{
using (scope.StartTry())
{
ctxList = ctxWeb.Lists.GetByTitle("Reusable Content");
CamlQuery qry = new CamlQuery();
qry.ViewXml = string.Format(ViewQueryByField, "Title", "Text", SharedContentTitle);
listItems = ctxList.GetItems(qry);
ctx.Load(listItems, items => items.Include(
item => item["Title"],
item => item["ReusableHtml"],
item => item["ReusableText"]));
}
using (scope.StartCatch()) { }
using (scope.StartFinally()) { }
}
ctx.ExecuteQuery();
if (scope.HasException)
{
result = string.Format("Error retrieving content<!-- Error Message: {0} | {1} -->", scope.ErrorMessage, contextUrl);
}
if (listItems.Count == 1)
{
Microsoft.SharePoint.Client.ListItem contentItem = listItems[0];
if (SelectedType == SharedContentType.Html)
{
result = contentItem["ReusableHtml"].ToString();
}
else if (SelectedType == SharedContentType.Text)
{
result = contentItem["ReusableText"].ToString();
}
}
}
I realize the part with the CredentialCache shouldn't be necessary in claims, but every single example I can find is either running in a console app, or in a client side application of some kind; this code is running in the codebehind of a regular ASP.NET UserControl.
Edit: I should probably mention, the code above doesn't even work when the remote URL is the root site collection on the same web app as the calling code (which is in a site collection under /sites/)--in other words, even when the hostname is the same as the calling code.
Any suggestions of what to try next are greatly appreciated!
Mike
Is there a reason why you are not using the standard OM?
You already said this is running in a web part, which means it is in the context of application pool account. Unless you elevate permissions by switching users, it won't authenticate correctly. Maybe try that. But I would not use the client OM when you do have access to the API already.

Resources