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.
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 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
I'm trying this to Create Directory in azureDataLake using azure data lake dependency
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-data-lake-store-sdk</artifactId>
<version>2.1.5</version>
</dependency>
Using the following method:
private ADLStoreClient client;
public boolean createDirectory(String path) {
try {
// create directory
client.createDirectory(path);
} catch (ADLException ex) {
printExceptionDetails(ex);
return false;
} catch (Exception ex) {
log.error(" Exception in createDirectory : {}", ex);
return false;
}
return true;
}
and I got this exception:
Error creating directory /gx-zweappdhd004/home/azhdipaasssh2/ADH/Compta/1458/1533632735200/RAPPORTS/
Operation MKDIRS failed with HTTP403 : AccessControlException
I checked the permission and I have all of them, so it's not related to the permissions.
Update:
To be more specefic the problem happening inside the method isSuccessfulResponse(), and exactlly in this line HttpTransport.java#L137 because the httpResponseCode equals to 403, can anybody explain this.
Update2:
I found that this line is returning the 403 status : HttpTransport.java#L288, I also tried to evaluate conn.getErrorStream().read() and I got this stream is closed, FYI this is bug occures sometimes and not always.
I didn't reproduce your issue,you could refer to my working code:
import com.microsoft.aad.adal4j.AuthenticationContext;
import com.microsoft.aad.adal4j.AuthenticationResult;
import com.microsoft.aad.adal4j.ClientCredential;
import com.microsoft.azure.datalake.store.ADLStoreClient;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CreateDirectory {
static ADLStoreClient client;
public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
setup();
}
public static void setup() throws IOException, ExecutionException, InterruptedException {
String APP_ID = "<your app id>";
String APP_SECRET = "<your app secret>";
String dirName = "/jay";
String StoreAcct = "jaygong";
String authority = "https://login.microsoftonline.com/<your tenant id>";
String resourcUrl = "https://management.core.windows.net/";
ExecutorService service = Executors.newFixedThreadPool(1);
AuthenticationContext context = new AuthenticationContext(authority, true, service);
// Acquire Token
Future<AuthenticationResult> result = context.acquireToken(
resourcUrl,
new ClientCredential(APP_ID, APP_SECRET),
null
);
String token = result.get().getAccessToken();
System.out.println(token);
String account = StoreAcct + ".azuredatalakestore.net";
client = ADLStoreClient.createClient(account, token);
client.createDirectory(dirName);
System.out.println("finish.....");
}
}
Don't forget grant access ADL permissons to your client.
Hope it helps you.
I found a code, which should reach the logged user:
InitialContext ic = new InitialContext();
SessionContext sessionContext = (SessionContext)ic.lookup("java:comp/EJBContext");
System.out.println("look up injected sctx: " + sessionContext);
Principal p = sessionContext.getCallerPrincipal();
System.out.println(p.getName());
But it still gives me <anonymus>. Why is that? How could I reach the logged user's name?
You can try this.
Subject subject = Subject.getSubject(AccessController.getContext());
Set<java.security.Principal> principals = s.getPrincipals();
for (java.security.Principal principal : principals) {
if (principal.getClass() == WLSUserImpl.class) {
return principal.getName();
}
}
Where WLSUserImpl is coming from package weblogic.security.principal.This is only workable for weblogic.
Your bean needs to be marked as secured (using any of the spec provided ways for the security related interceptors to play a role).
As a first step, you could do something like:
#Override
#PermitAll
public String whoAmI() {
return context.getCallerPrincipal().getName();
}
That's just an example where you allow all roles to access that method. The presence of that #PermitAll security annotation will instruct the EJB container to bring into picture the EJB security interceptors. Take a look at this documentation for further details .Giving you jboss example
https://docs.jboss.org/author/display/AS72/Securing+EJBs
You can use mbean API also to get it
import javax.naming.*;
import javax.management.MBeanInfo;
import weblogic.jndi.Environment;
import weblogic.management.runtime.ServerRuntimeMBean;
import weblogic.security.providers.authentication.DefaultAuthenticatorMBean;
import weblogic.management.security.authentication.UserReaderMBean;
import weblogic.management.security.authentication.GroupReaderMBean;
import weblogic.management.MBeanHome;
import weblogic.management.WebLogicMBean;
import weblogic.management.tools.Info;
import weblogic.management.Helper;
import weblogic.management.security.authentication.*;
public class ListUsersAndGroups
{
public static void main(String[] args)
{
MBeanHome home = null;
try
{
Environment env = new Environment();
env.setProviderUrl(“t3://localhost:7001?);
env.setSecurityPrincipal(“weblogic”);
env.setSecurityCredentials(“weblogic”);
Context ctx = env.getInitialContext();
home = (MBeanHome)ctx.lookup(“weblogic.management.adminhome”);
weblogic.management.security.RealmMBean rmBean = home.getActiveDomain().getSecurityConfiguration().getDefaultRealm();
AuthenticationProviderMBean[] authenticationBeans = rmBean.getAuthenticationProviders();
DefaultAuthenticatorMBean defaultAuthenticationMBean = (DefaultAuthenticatorMBean)authenticationBeans[0];
UserReaderMBean userReaderMBean = (UserReaderMBean)defaultAuthenticationMBean;
GroupReaderMBean groupReaderMBean = (GroupReaderMBean)defaultAuthenticationMBean;
String userCurName = userReaderMBean.listUsers(“*”, 100);
while (userReaderMBean.haveCurrent(userCurName) )
{
String user = userReaderMBean.getCurrentName(userCurName);
System.out.println(“\n User: ” + user);
userReaderMBean.advance(userCurName);
}
String cursorName = groupReaderMBean.listGroups(“*”, 100);
while (groupReaderMBean.haveCurrent(cursorName) )
{
String group = groupReaderMBean.getCurrentName(cursorName);
System.out.println(“\n Group: ” + group);
groupReaderMBean.advance(cursorName);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}