I am struggling with the following issue while trying to retrieve all GPO of a domain with Java. I was able to create a connection to Active Directory and get the policy objects, however I am not able to retrieve their settings in which I am interested in.
I was only able to retrieve the following properties:
CanonicalName
CN
Created
createTimeStamp
Deleted
Description
DisplayName
DistinguishedName
dSCorePropagationData
flags
gPCFileSysPath
gPCFunctionalityVersion
gPCMachineExtensionNames
gPCUserExtensionNames
instanceType
isCriticalSystemObject
isDeleted
LastKnownParent
Modified
modifyTimeStamp
Name
nTSecurityDescriptor
ObjectCategory
ObjectClass
ObjectGUID
ProtectedFromAccidentalDeletion
sDRightsEffective
showInAdvancedViewOnly
systemFlags
uSNChanged
uSNCreated
versionNumber
whenChanged
whenCreated
Do you know how should I face this issue? Is there any extended property from which I can retrieve the settings of each GPO?
I do not know if the code would be useful as it is just a connection and a ldap query:
colAttributes = {"*"};
strSearchRoot = "DC=xx,DC=xx";
this.getActiveDirectoryConnection().setRequestControl(null, Control.NONCRITICAL);
colSearchResult = this.getActiveDirectoryConnection().getQuery(colAttributes, "(ObjectClass=groupPolicyContainer)", strSearchRoot);
while (colSearchResult.hasMoreElements())
{
objSearchResult = (SearchResult) colSearchResult.nextElement();
objAttributes = objSearchResult.getAttributes();
}
private void getActiveDirectoryConnection()
{
return new ActiveDirectory(strDomain, strUsername, strPassword);
}
An example of I am trying to get is the Default Domain Policy, not only this but all policies. And settings goes through Password Settings such as maxPwdAge, lockoutThreshold, etc Screen and Power Settings, between others
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.PagedResultsControl;
import javax.naming.ldap.PagedResultsResponseControl;
public class ActiveDirectory
{
private LdapContext objLDAPContext;
public ActiveDirectory(String strURL, String strUserName, String strPassword) throws NamingException
{
Hashtable<String, Object> objEnvironment;
objEnvironment = new Hashtable<String, Object>(11);
objEnvironment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
objEnvironment.put(Context.PROVIDER_URL, strURL);
objEnvironment.put(Context.SECURITY_AUTHENTICATION, "simple");
objEnvironment.put(Context.SECURITY_PRINCIPAL, strUserName);
objEnvironment.put(Context.SECURITY_CREDENTIALS, strPassword);
objEnvironment.put("java.naming.ldap.attributes.binary", "objectGUID");
try
{
this.objLDAPContext = new InitialLdapContext(objEnvironment, null);
}
catch (NamingException objException)
{
System.setProperty("javax.net.ssl.trustStore", "certificates".concat(File.separator).concat("cacerts"));
objEnvironment.put(Context.PROVIDER_URL, strURL.replace("LDAP:", "LDAPS:").replace(":389", ":636"));
}
this.objLDAPContext = new InitialLdapContext(objEnvironment, null);
}
private LdapContext getContext()
{
return this.objLDAPContext;
}
public NamingEnumeration<SearchResult> getQuery(String[] colAttributes, String strLDAPFilter, String strSearchRoot) throws NamingException
{
NamingEnumeration<SearchResult> objAnswer;
SearchControls objSearchControls = new SearchControls();
objSearchControls.setReturningAttributes(colAttributes);
objSearchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
objAnswer = this.getContext().search(strSearchRoot, strLDAPFilter, objSearchControls);
return objAnswer;
}
public void close() throws NamingException
{
this.getContext().close();
}
public void setRequestControl(byte[] objCookie, boolean bolControl)
{
int intPageSize;
intPageSize = 1000;
try
{
this.getContext().setRequestControls(new Control[]
{
new PagedResultsControl(intPageSize, objCookie, bolControl)
});
}
catch(NamingException | IOException objException)
{
//No more pages could be recovered
}
}
public byte[] getCookie()
{
byte[] objCookie;
objCookie = null;
try
{
Control[] objControl = this.getContext().getResponseControls();
if (objControl != null)
{
for (int intCounter = 0; intCounter < objControl.length; intCounter++)
{
if (objControl[intCounter] instanceof PagedResultsResponseControl)
{
PagedResultsResponseControl objPagedControl = (PagedResultsResponseControl) objControl[intCounter];
objCookie = objPagedControl.getCookie();
}
}
}
}
catch(NamingException objException)
{
//Skip errors null cookie will be handled
}
return objCookie;
}
}
You can't get gpo settings through LDAP, because gpo templates has been stored in sysvol folder in domain controller.It is a shared folder across the domain. We can get the path of GPO templates by GPO container attribute gPLink. If you access the file you can get all applied gpo settings
Related
I am developing a simple java app that show the pods of the cluster.
This is the app:
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodList;
import io.kubernetes.client.util.ClientBuilder;
import io.kubernetes.client.util.KubeConfig;
import java.io.FileReader;
import java.io.IOException;
/**
* A simple example of how to use the Java API from an application outside a kubernetes cluster
*
* <p>Easiest way to run this: mvn exec:java
* -Dexec.mainClass="io.kubernetes.client.examples.KubeConfigFileClientExample"
*
*/
public class untitled4 {
public static void main(String[] args) throws IOException, ApiException {
// file path to your KubeConfig
String kubeConfigPath = "/home/robin/.kube/config";
// loading the out-of-cluster config, a kubeconfig from file-system
ApiClient client =
ClientBuilder.kubeconfig(KubeConfig.loadKubeConfig(new FileReader(kubeConfigPath))).build();
// set the global default api-client to the in-cluster one from above
Configuration.setDefaultApiClient(client);
// the CoreV1Api loads default api-client from global configuration.
CoreV1Api api = new CoreV1Api();
// invokes the CoreV1Api client
V1PodList list = api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
System.out.println("Listing all pods: ");
for (V1Pod item : list.getItems()) {
System.out.println(item.getMetadata().getName());
}
}
}
But I get this error:
Exception in thread "main" java.lang.IllegalStateException: Unimplemented
at io.kubernetes.client.util.authenticators.GCPAuthenticator.refresh(GCPAuthenticator.java:61)
at io.kubernetes.client.util.KubeConfig.getAccessToken(KubeConfig.java:215)
at io.kubernetes.client.util.credentials.KubeconfigAuthentication.<init>(KubeconfigAuthentication.java:46)
at io.kubernetes.client.util.ClientBuilder.kubeconfig(ClientBuilder.java:276)
at untitled4.main(untitled4.java:28)
Process finished with exit code 1
There is an open issue on GitHub related with this problem. For now you can use workarounds like the one, proposed by jhbae200 in this comment:
I am using it like this.
package kubernetes.gcp;
import com.google.auth.oauth2.AccessToken;
import com.google.auth.oauth2.GoogleCredentials;
import io.kubernetes.client.util.KubeConfig;
import io.kubernetes.client.util.authenticators.Authenticator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.time.Instant;
import java.util.Date;
import java.util.Map;
public class ReplacedGCPAuthenticator implements Authenticator {
private static final Logger log;
private static final String ACCESS_TOKEN = "access-token";
private static final String EXPIRY = "expiry";
static {
log = LoggerFactory.getLogger(io.kubernetes.client.util.authenticators.GCPAuthenticator.class);
}
private final GoogleCredentials credentials;
public ReplacedGCPAuthenticator(GoogleCredentials credentials) {
this.credentials = credentials;
}
public String getName() {
return "gcp";
}
public String getToken(Map<String, Object> config) {
return (String) config.get("access-token");
}
public boolean isExpired(Map<String, Object> config) {
Object expiryObj = config.get("expiry");
Instant expiry = null;
if (expiryObj instanceof Date) {
expiry = ((Date) expiryObj).toInstant();
} else if (expiryObj instanceof Instant) {
expiry = (Instant) expiryObj;
} else {
if (!(expiryObj instanceof String)) {
throw new RuntimeException("Unexpected object type: " + expiryObj.getClass());
}
expiry = Instant.parse((String) expiryObj);
}
return expiry != null && expiry.compareTo(Instant.now()) <= 0;
}
public Map<String, Object> refresh(Map<String, Object> config) {
try {
AccessToken accessToken = this.credentials.refreshAccessToken();
config.put(ACCESS_TOKEN, accessToken.getTokenValue());
config.put(EXPIRY, accessToken.getExpirationTime());
} catch (IOException e) {
throw new RuntimeException(e);
}
return config;
}
}
Running in.
//GoogleCredentials.fromStream(--something credential.json filestream--)
KubeConfig.registerAuthenticator(new ReplacedGCPAuthenticator(GoogleCredentials.getApplicationDefault()));
ApiClient client = Config.defaultClient();
Configuration.setDefaultApiClient(client);
CoreV1Api api = new CoreV1Api();
V1PodList list = api.listNamespacedPod("default", null, null, null, null, null, null, null, 30, Boolean.FALSE);
for (V1Pod item : list.getItems()) {
System.out.println(item.getMetadata().getName());
}
So I am trying to authorize specific groups with ActiveMQ. I know the following:
Authentication works, but as soon as I add "AuthorizationPlugin" to
my ActiveMQ.xml, I start to get an error.
I used the default "ModuleClass" that points to "org.apache.activemq.jaas.PropertiesLoginModule". This works with both Authentication and Authorization (which confuses me more).
I have tried copying the contents of PropertiesLoginModule, re-creating the jar and trying to have it work, but that too still gives the same error.
The error that I am getting is:
java.lang.SecurityException: User user is not authorized to create: topic://ActiveMQ.Advisory.Connection
at org.apache.activemq.security.AuthorizationBroker.addDestination(AuthorizationBroker.java:115)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.broker.BrokerFilter.addDestination(BrokerFilter.java:174)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.broker.region.RegionBroker.send(RegionBroker.java:454)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.broker.jmx.ManagedRegionBroker.send(ManagedRegionBroker.java:293)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.advisory.AdvisoryBroker.fireAdvisory(AdvisoryBroker.java:909)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.advisory.AdvisoryBroker.fireAdvisory(AdvisoryBroker.java:836)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.advisory.AdvisoryBroker.fireAdvisory(AdvisoryBroker.java:831)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.advisory.AdvisoryBroker.addConnection(AdvisoryBroker.java:125)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.broker.BrokerFilter.addConnection(BrokerFilter.java:99)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.broker.BrokerFilter.addConnection(BrokerFilter.java:99)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.broker.BrokerFilter.addConnection(BrokerFilter.java:99)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.security.JaasAuthenticationBroker.addConnection(JaasAuthenticationBroker.java:71)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.broker.BrokerFilter.addConnection(BrokerFilter.java:99)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.broker.BrokerFilter.addConnection(BrokerFilter.java:99)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.broker.TransportConnection.processAddConnection(TransportConnection.java:849)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.broker.jmx.ManagedTransportConnection.processAddConnection(ManagedTransportConnection.java:77)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.command.ConnectionInfo.visit(ConnectionInfo.java:139)[activemq-client-5.15.9.jar:5.15.9]
at org.apache.activemq.broker.TransportConnection.service(TransportConnection.java:336)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.broker.TransportConnection$1.onCommand(TransportConnection.java:200)[activemq-broker-5.15.9.jar:5.15.9]
at org.apache.activemq.transport.MutexTransport.onCommand(MutexTransport.java:50)[activemq-client-5.15.9.jar:5.15.9]
at org.apache.activemq.transport.WireFormatNegotiator.onCommand(WireFormatNegotiator.java:125)[activemq-client-5.15.9.jar:5.15.9]
at org.apache.activemq.transport.AbstractInactivityMonitor.onCommand(AbstractInactivityMonitor.java:301)[activemq-client-5.15.9.jar:5.15.9]
at org.apache.activemq.transport.TransportSupport.doConsume(TransportSupport.java:83)[activemq-client-5.15.9.jar:5.15.9]
at org.apache.activemq.transport.tcp.TcpTransport.doRun(TcpTransport.java:233)[activemq-client-5.15.9.jar:5.15.9]
at org.apache.activemq.transport.tcp.TcpTransport.run(TcpTransport.java:215)[activemq-client-5.15.9.jar:5.15.9]
at java.lang.Thread.run(Thread.java:748)[:1.8.0_211]
I don't think there's a problem with my configuration since it works with the default PropertiesLoginModule. But just incase, here's my configuration:
activemq.xml
activemq-domain {
org.apache.activemq.jaas.PropertiesLoginModule required
debug=false
org.apache.activemq.jaas.properties.user="users.properties"
org.apache.activemq.jaas.properties.group="groups.properties";
};
custom-login {
x.x.x.x.MyCustomModule required
debug=false
org.apache.activemq.jaas.properties.user="users.properties"
org.apache.activemq.jaas.properties.group="groups.properties";
};
users.properties
admin=admin
user=password
publisher=password
consumer=password
guest=password
groups.properties
admins=admin
users=user,admin
publishers=admin,publisher
consumers=admin,publisher,consumer
guests=guest
activemq.xml
<plugins>
<!-- For Authentication -->
<jaasAuthenticationPlugin configuration="custom-login"/>
<!-- For Authorization -->
<authorizationPlugin>
<map>
<authorizationMap>
<authorizationEntries>
<authorizationEntry queue=">" read="admins" write="admins,users" admin="admins"/>
<authorizationEntry queue="USERS.>" read="users" write="users" admin="users"/>
<authorizationEntry queue="GUEST.>" read="guests" write="guests,users" admin="guests,users"/>
<authorizationEntry topic=">" read="admins" write="admins,users" admin="admins"/>
<authorizationEntry topic="USERS.>" read="users" write="users" admin="users"/>
<authorizationEntry topic="GUEST.>" read="guests" write="guests,users" admin="guests,users"/>
<authorizationEntry topic="ActiveMQ.Advisory.>" read="guests,users,admins" write="guests,users,admins" admin="guests,users,admins"/>
</authorizationEntries>
</authorizationMap>
</map>
</authorizationPlugin>
</plugins>
Can anybody shed some light on this? I think I have exhausted Google.
Am I missing anything in the configuration (or doing anything wrong in the process)? Why does this work with the default ModuleClass but not my custom login module, despite me re-creating the jar?
Has anybody gotten authorization to work with their own custom JAAS login plugin?
Thanks.
Edit:
JAAS Login Module:
package cz.net21;
import java.io.File;
import java.io.IOException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import org.apache.activemq.jaas.GroupPrincipal;
import org.apache.activemq.jaas.UserPrincipal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* #author ttulka
*
*/
public class ActiveMqLoginModule implements LoginModule {
private static final Logger LOG = LoggerFactory.getLogger(ActiveMqLoginModule.class);
private static final String PASSWORD = "pass"; // we demand this password for all the users
private static final String GROUP_FILE = "org.apache.activemq.jaas.properties.group";
private CallbackHandler callbackHandler;
private Subject subject;
private Set<Principal> principals = new HashSet<>();
private String user; // username
private Properties groups = new Properties();
// the authentication status
private boolean succeeded = false;
private boolean commitSucceeded = false;
private File baseDir;
private String groupsFile;
#Override
public void initialize(Subject subject, CallbackHandler handler, Map<String, ?> state, Map<String, ?> options) {
this.subject = subject;
this.callbackHandler = handler;
// set up a name of the file for groups
if (System.getProperty("java.security.auth.login.config") != null) {
baseDir = new File(System.getProperty("java.security.auth.login.config")).getParentFile();
} else {
baseDir = new File(".");
}
if (!options.containsKey(GROUP_FILE)) {
LOG.warn("The group properties file path must be set by a parameter {}.", GROUP_FILE);
} else {
groupsFile = options.get(GROUP_FILE) + "";
}
}
#Override
public boolean login() throws LoginException {
if (callbackHandler == null) {
throw new LoginException("No callback handler supplied.");
}
// load groups properties
try {
File f = new File(baseDir, groupsFile);
groups.load(new java.io.FileInputStream(f));
}
catch (IOException e) {
throw new LoginException("Unable to load group properties file " + groupsFile);
}
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("Username");
callbacks[1] = new PasswordCallback("Password", false);
try {
callbackHandler.handle(callbacks);
String username = ((NameCallback) callbacks[0]).getName();
char[] passwordCharArray = ((PasswordCallback) callbacks[1]).getPassword();
String password = new String(passwordCharArray);
subject.getPublicCredentials().add(username);
subject.getPrivateCredentials().add(password);
user = username;
// TODO authentication.
succeeded = PASSWORD.equals(password);
}
catch (IOException e) {
LOG.error(e.getMessage());
throw new LoginException("IOException occured.");
}
catch (UnsupportedCallbackException e) {
LOG.error(e.getMessage());
throw new LoginException("UnsupportedCallbackException encountered.");
}
return succeeded;
}
/**
* Authentication successful
*/
#Override
public boolean commit() throws LoginException {
if (succeeded == false) {
return false;
}
// set up the user
principals.add(new UserPrincipal(user));
// set up the groups for the user
for (Enumeration<?> enumeration = groups.keys(); enumeration.hasMoreElements();) {
String groupName = (String) enumeration.nextElement();
String[] userList = ((String) groups.getProperty(groupName) + "").split(",");
for (int i = 0; i < userList.length; i++) {
if (user.equals(userList[i])) {
principals.add(new GroupPrincipal(groupName));
break;
}
}
}
subject.getPrincipals().addAll(principals);
commitSucceeded = true;
clear();
return true;
}
#Override
public boolean logout() throws LoginException {
subject.getPrincipals().removeAll(principals);
principals.clear();
succeeded = false;
commitSucceeded = false;
return true;
}
/**
* Authentication failure
*/
#Override
public boolean abort() throws LoginException {
clear();
if (succeeded == false) {
return false;
}
if (succeeded == true && commitSucceeded == false) {
// login succeeded but overall authentication failed
succeeded = false;
} else {
// overall authentication succeeded and commit succeeded,
// but someone else's commit failed
logout();
}
return true;
}
private void clear() {
groups.clear();
user = null;
}
}
(From here: http://blog.ttulka.com/activemq-jaas-custom-login-module)
I am developing a Java client which creates the service provider dynamically with Inbound Authentication set to OAuth in WSO2 Identity Server. The code goes as follows
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Map;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.transport.http.HttpTransportProperties;
import org.wso2.carbon.authenticator.proxy.AuthenticationAdminStub;
import org.wso2.carbon.um.ws.api.WSRealmBuilder;
import org.wso2.carbon.um.ws.api.stub.ClaimValue;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.UserStoreManager;
import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider;
import org.wso2.carbon.identity.application.mgt.stub.IdentityApplicationManagementServiceStub;
import org.wso2.carbon.identity.oauth.stub.*;
import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO;
public class IdentityClient {
private final static String SERVER_URL = "https://localhost:9443/services/";
public static void main(String[] args) throws RemoteException, OAuthAdminServiceException {
String appName = "Sample_App_3";
System.setProperty("javax.net.ssl.trustStore", "wso2carbon.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
try {
OAuthAdminServiceStub stub = new OAuthAdminServiceStub(null,
SERVER_URL + "OAuthAdminService");
IdentityApplicationManagementServiceStub IAMStub = new IdentityApplicationManagementServiceStub(
null, SERVER_URL + "IdentityApplicationManagementService");
ServiceClient client = stub._getServiceClient();
ServiceClient IAMClient = IAMStub._getServiceClient();
authenticate(client);
OAuthConsumerAppDTO consumerApp = new OAuthConsumerAppDTO();
consumerApp.setApplicationName(appName);
consumerApp.setOAuthVersion("OAuth-2.0");
consumerApp.setCallbackUrl("http://localhost:8080/playground2/oauth2client");
consumerApp.setGrantTypes(
"authorization_code implicit password client_credentials refresh_token "
+ "urn:ietf:params:oauth:grant-type:saml2-bearer iwa:ntlm");
/* OAuthAdminProxy.registerOAuthApplicationData(consumerApp); */
stub.registerOAuthApplicationData(consumerApp);
System.out.println("Application created successfully");
authenticate(IAMClient);
InboundAuthenticationRequestConfig iaReqConfig = new InboundAuthenticationRequestConfig();
iaReqConfig.setInboundAuthKey(stub.getOAuthApplicationDataByAppName(appName)
.getOauthConsumerKey());
iaReqConfig.setInboundAuthType(stub.getOAuthApplicationDataByAppName(appName)
.getOauthConsumerSecret());
InboundAuthenticationRequestConfig[] iaReqConfigList = { iaReqConfig };
InboundAuthenticationConfig ib = new InboundAuthenticationConfig();
ib.setInboundAuthenticationRequestConfigs(iaReqConfigList);
ServiceProvider serviceProvider = new ServiceProvider();
serviceProvider.setApplicationName(
stub.getOAuthApplicationDataByAppName(appName).getApplicationName());
serviceProvider.setInboundAuthenticationConfig(ib);
IAMStub.createApplication(serviceProvider);
System.out.println("Service Provider created");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void authenticate(ServiceClient client) {
Options option = client.getOptions();
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
auth.setUsername("admin");
auth.setPassword("admin");
auth.setPreemptiveAuthentication(true);
option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
option.setManageSession(true);
}
}
Once I run this code, the service provider is getting created in the WSO2 Identity Server which I could see in the management console. The OAuth configuration which has been done vis-a-vis the service provider is not showing up and it is empty with just a 'configure' link. Had I understood WSO2 IS properly then I should be getting the consumer key and consumer secret under Inbound Authentication Configuration --> OAuth/OpenID Connect Configuration drop down.
Please help me in what should be done right ?
Try changing your client as bellow,
import java.rmi.RemoteException;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.transport.http.HttpTransportProperties;
import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.xsd.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.xsd.Property;
import org.wso2.carbon.identity.application.common.model.xsd.ServiceProvider;
import org.wso2.carbon.identity.application.mgt.stub.IdentityApplicationManagementServiceStub;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceException;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO;
public class IdentityClient {
private final static String SERVER_URL = "https://localhost:9443/services/";
public static void main(String[] args) throws RemoteException, OAuthAdminServiceException {
String appName = "Sample_App_5";
String appDescription = "Test description";
System.setProperty("javax.net.ssl.trustStore", "wso2carbon.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
try {
OAuthAdminServiceStub stub = new OAuthAdminServiceStub(null,
SERVER_URL + "OAuthAdminService");
IdentityApplicationManagementServiceStub IAMStub = new IdentityApplicationManagementServiceStub(
null, SERVER_URL + "IdentityApplicationManagementService");
ServiceClient client = stub._getServiceClient();
ServiceClient IAMClient = IAMStub._getServiceClient();
authenticate(client);
authenticate(IAMClient);
ServiceProvider serviceProvider = new ServiceProvider();
serviceProvider.setApplicationName(appName);
serviceProvider.setDescription(appDescription);
IAMStub.createApplication(serviceProvider);
OAuthConsumerAppDTO consumerApp = new OAuthConsumerAppDTO();
consumerApp.setApplicationName(appName);
consumerApp.setOAuthVersion("OAuth-2.0");
consumerApp.setCallbackUrl("http://localhost:8080/playground2/oauth2client");
consumerApp.setGrantTypes(
"authorization_code implicit password client_credentials refresh_token "
+ "urn:ietf:params:oauth:grant-type:saml2-bearer iwa:ntlm");
/* OAuthAdminProxy.registerOAuthApplicationData(consumerApp); */
stub.registerOAuthApplicationData(consumerApp);
System.out.println("Application created successfully");
System.out.println(stub.getOAuthApplicationDataByAppName(appName).getOauthConsumerKey());
authenticate(IAMClient);
InboundAuthenticationRequestConfig iaReqConfig = new InboundAuthenticationRequestConfig();
iaReqConfig.setInboundAuthKey(stub.getOAuthApplicationDataByAppName(appName).getOauthConsumerKey());
iaReqConfig.setInboundAuthType("oauth2");
Property property = new Property();
property.setName("oauthConsumerSecret");
property.setValue(stub.getOAuthApplicationDataByAppName(appName).getOauthConsumerSecret());
Property[] properties = { property };
iaReqConfig.setProperties(properties);
InboundAuthenticationRequestConfig[] iaReqConfigList = { iaReqConfig };
InboundAuthenticationConfig ib = new InboundAuthenticationConfig();
ib.setInboundAuthenticationRequestConfigs(iaReqConfigList);
serviceProvider = IAMStub.getApplication(appName);
serviceProvider.setApplicationName(
stub.getOAuthApplicationDataByAppName(appName).getApplicationName());
serviceProvider.setInboundAuthenticationConfig(ib);
IAMStub.updateApplication(serviceProvider);
System.out.println("Service Provider created");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void authenticate(ServiceClient client) {
Options option = client.getOptions();
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
auth.setUsername("admin");
auth.setPassword("admin");
auth.setPreemptiveAuthentication(true);
option.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, auth);
option.setManageSession(true);
}
}
Problem is createApplication does not save the configurations other than the name and the description. You have to call updateApplication to save other application configurations.
I'm trying to make a search through the Fedora Commons web service. I'm interested in the findObjects method. How can I make a search in Java equal to the example described on the findObjects syntax documentation.
I'm particularly interested in this type of request:
http://localhost:8080/fedora/search?terms=fedora&pid=true&title=true
I'll attach some code, I have a class that can call my Fedora service already.
package test.fedora;
import info.fedora.definitions._1._0.types.DatastreamDef;
import info.fedora.definitions._1._0.types.MIMETypedStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import javax.xml.ws.BindingProvider;
import org.w3c.dom.Document;
public class FedoraAccessor {
info.fedora.definitions._1._0.api.FedoraAPIAService service;
info.fedora.definitions._1._0.api.FedoraAPIA port;
final String username = "xxxx";
final String password = "yyyy";
public FedoraAClient() {
service = new info.fedora.definitions._1._0.api.FedoraAPIAService();
port = service.getFedoraAPIAServiceHTTPPort();
((BindingProvider) port.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
}
public List findObjects() {
//how?
}
public List<DatastreamDef> listDatastreams(String pid, String asOfTime) {
List<DatastreamDef> result = null;
try {
result = port.listDatastreams(pid, asOfTime);
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
}
It's easier using the client from mediashelf (http://mediashelf.github.com/fedora-client/). Here's an example searching for objects containing the string foobar in the title:
#Test
public void doTest() throws FedoraClientException {
connect();
FindObjectsResponse response = null;
response = findObjects().pid().title().query("title~foobar").execute(fedoraClient);
List<String> pids = response.getPids();
List<String> titles = new ArrayList<String>();
for (String pid : pids) {
titles.add(response.getObjectField(pid, "title").get(0));
}
assertEquals(7, titles.size());
}
This question already has answers here:
NullPointerException when setting attribute?
(5 answers)
Closed 7 years ago.
I have to make a litle change to an existing project(tomcat and java WebApplication).
now, in loginForm, if users type correct login and password, it is Ok,
to users wil be shown main page. But when any user types incorrect password,
or may be his account is temporarily locked, so to user again wil be shown loginform,
user can not know why he cannot log in, by what cause he can not login.
(for example "invalid username/password","user account locked",...).
now i want to insert the session error message that includes also causes of why user cannot log in.
insert(save) to session an attribute named "LoggingError".
i am writing as:
request.getSession().setAttribute("LoggingError", message);
but when running application, in this line
request.getSession().setAttribute("LoggingError", message);
occurs error in web page:
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
com.se.eee.security.EeeAuthenticationProvider.authenticate(EeeAuthenticationProvider.java:153)
net.sf.acegisecurity.providers.ProviderManager.doAuthentication(ProviderManager.java:159)
net.sf.acegisecurity.AbstractAuthenticationManager.authenticate(AbstractAuthenticationManager.java:49)
net.sf.ace
...
...
here java code of EeeAuthenticationProvider.java
package com.se.eee.security;
import net.sf.acegisecurity.*;
import net.sf.acegisecurity.providers.AuthenticationProvider;
import net.sf.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import net.sf.acegisecurity.providers.dao.User;
import net.sf.acegisecurity.providers.dao.UsernameNotFoundException;
import net.sf.acegisecurity.providers.dao.event.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import com.se.eee.bus.*;
import com.se.eee.bus.SecurityManager;
import com.se.spring.datasource.core.MakeConnectionException;
import com.se.spring.ext.CurrentRequestContext;
import com.opensymphony.webwork.interceptor.SessionAware;
import com.opensymphony.webwork.interceptor.ServletRequestAware;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
public class EeeAuthenticationProvider implements AuthenticationProvider, SessionAware, ServletRequestAware {
private static Log log = LogFactory.getLog(EeeAuthenticationProvider.class);
private JDBCProperties jdbcProp;
private ApplicationContext context;
private SecurityManager securityManager;
private HttpServletRequest request;
public void setServletRequest(HttpServletRequest req) {
this.request = req;
}
public void setSession(Map session) {
//To change body of implemented methods use File | Settings | File Templates.
}
public void setSecurityManager(SecurityManager securityManager) {
this.securityManager = securityManager;
}
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context = applicationContext;
}
public void setJdbcProp(JDBCProperties jdbcProp) {
this.jdbcProp = jdbcProp;
}
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// Determine username
// log.warn((authentication.isAuthenticated()?"Already Authenticated. Skip it!":"")+"authenticate: "+authentication);
if(authentication.isAuthenticated()) {
//log.warn("Already Authenticated. Skip it!");
return authentication;
}
String username = "NONE_PROVIDED";
if (authentication.getPrincipal() != null) {
username = authentication.getPrincipal().toString();
}
if (authentication.getPrincipal() instanceof UserDetails) {
username = ((UserDetails) authentication.getPrincipal()).getUsername();
}
UserDetails user = null;
com.se.eee.bus.User principal=null;
try
{
JDBCProperties props = jdbcProp.deserialize();
String input_passwords= authentication.getCredentials().toString();
String[] psd = input_passwords.split(":");
Filial fil = props.getFilial(psd[1]);
String sgn = input_passwords;
int i= sgn.indexOf(":", 1);
sgn = sgn.substring(i+1,sgn.length());
i= sgn.indexOf(":", 1);
sgn = sgn.substring(i+1,sgn.length());
if(fil==null)username=null;
securityManager.makeConnect(username, psd[0], fil);
user=new User(username, "skipped",true,true,true,true, new GrantedAuthority[]{new GrantedAuthorityImpl("ROLE_USER")});
//set connection for DataSource
ContextDataBean dataBean=(ContextDataBean)CurrentRequestContext.get();
dataBean.setUserKey(username+fil.id);
principal=securityManager.getUserByLogin(username.toUpperCase());
if(principal == null) throw new UsernameNotFoundException("Couldn't login.");
principal.setLogin(username);
principal.setPassword("******");
//principal.setBranch(fil.id);
if (principal.getBanktype().equals("055"))
{
if ( sgn!=null && sgn.length() != 0)
{
securityManager.insUserKey(principal.getBranch(), principal.getId(), sgn);
com.se.eee.bus.Document docum = new com.se.eee.bus.Document();
docum.setBranch(principal.getBranch());
docum.setEmpId(principal.getId());
docum.setErrCode("991");
docum = securityManager.getAnswerUserKey(docum);
if (!docum.getErrCode().equals("000")) throw new UsernameNotFoundException("Key code error. User: "+principal.getLogin());
}
else
{
throw new UsernameNotFoundException("error while inserting test key code. please touch i-key or check loginform.ftl. user: "+principal.getLogin());
}
}
}
catch (MakeConnectionException mex)
{
log.error(mex.getMessage());
if (this.context != null) {
context.publishEvent(new AuthenticationFailureUsernameOrPasswordEvent(authentication, new User("".equals(username)? "EMPTY_STRING_PROVIDED" : username, "*****", false, false, false, false, new GrantedAuthority[0])));
}
throw new BadCredentialsException("Couldn't login connection problem.");
}
catch(Exception ex)
{
Throwable cause=ex.getCause();
String message=null;
if(cause!=null)message = cause.getMessage();
else message = ex.toString();
log.error(message);
// здес я пытаюс написать в session
request.getSession().setAttribute("LoggingError", message);
// но код не компилируется
throw new UsernameNotFoundException("Couldn't login.");
}
return createSuccessAuthentication(principal, authentication, user);
}
protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal, authentication.getCredentials(), user.getAuthorities());
result.setDetails((authentication.getDetails() != null) ? authentication.getDetails() : null);
result.setAuthenticated(true);
return result;
}
public boolean supports(Class aClass) {
if (UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass)) return true;
return false;
}
}
If your request object is a HttpServletRequest object then this should work.
If this isn't the problem can you send the exact code snippet (shouldn't need the whole program) and the exact error message?
this should work.
request.getSession(true).setAttribute("LoggingError", message);
Is your authentication provider specified as prototype scope bean? Not sure how Struts / WebWork is exactly integrated with Spring, but if your bean is singleton, it can not work.
In other words, make sure setServletRequest is called.
And by the way this application must be pretty old, if it has such package names as it has.