use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project karaf by apache.
the class SyncopeBackingEngine method listRolesSyncope2.
private List<RolePrincipal> listRolesSyncope2(Principal principal) {
List<RolePrincipal> result = new ArrayList<>();
HttpGet request = new HttpGet(address + "/users/" + principal.getName());
request.setHeader("Content-Type", "application/json");
try {
HttpResponse httpResponse = client.execute(request);
String response = EntityUtils.toString(httpResponse.getEntity());
if (response != null && !response.isEmpty()) {
JSONParser parser = new JSONParser(response);
List<String> roles = (List<String>) parser.getParsed().get("roles");
for (String role : roles) {
result.add(new RolePrincipal(role));
}
}
} catch (Exception e) {
throw new RuntimeException("Error listing roles", e);
}
return result;
}
use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project karaf by apache.
the class LDAPLoginModule method doLogin.
protected boolean doLogin() throws LoginException {
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("Username: ");
callbacks[1] = new PasswordCallback("Password: ", false);
try {
callbackHandler.handle(callbacks);
} catch (IOException ioException) {
throw new LoginException(ioException.getMessage());
} catch (UnsupportedCallbackException unsupportedCallbackException) {
throw new LoginException(unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
}
user = Util.doRFC2254Encoding(((NameCallback) callbacks[0]).getName());
char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
// If either a username or password is specified don't allow authentication = "none".
// This is to prevent someone from logging into Karaf as any user without providing a
// valid password (because if authentication = none, the password could be any
// value - it is ignored).
LDAPOptions options = new LDAPOptions(this.options);
if (options.isUsernameTrim()) {
if (user != null) {
user = user.trim();
}
}
String authentication = options.getAuthentication();
if ("none".equals(authentication) && (user != null || tmpPassword != null)) {
logger.debug("Changing from authentication = none to simple since user or password was specified.");
// default to simple so that the provided user/password will get checked
authentication = "simple";
Map<String, Object> opts = new HashMap<>(this.options);
opts.put(LDAPOptions.AUTHENTICATION, authentication);
options = new LDAPOptions(opts);
}
boolean allowEmptyPasswords = options.getAllowEmptyPasswords();
if (!"none".equals(authentication) && !allowEmptyPasswords && (tmpPassword == null || tmpPassword.length == 0)) {
throw new LoginException("Empty passwords not allowed");
}
if (tmpPassword == null) {
tmpPassword = new char[0];
}
String password = new String(tmpPassword);
principals = new HashSet<>();
LDAPCache cache = LDAPCache.getCache(options);
// step 1: get the user DN
final String[] userDnAndNamespace;
try {
logger.debug("Get the user DN.");
userDnAndNamespace = cache.getUserDnAndNamespace(user);
if (userDnAndNamespace == null) {
return false;
}
} catch (Exception e) {
logger.warn("Can't connect to the LDAP server: {}", e.getMessage(), e);
throw new LoginException("Can't connect to the LDAP server: " + e.getMessage());
}
// step 2: bind the user using the DN
DirContext context = null;
try {
// switch the credentials to the Karaf login user so that we can verify his password is correct
logger.debug("Bind user (authentication).");
Hashtable<String, Object> env = options.getEnv();
env.put(Context.SECURITY_AUTHENTICATION, authentication);
logger.debug("Set the security principal for " + userDnAndNamespace[0] + "," + options.getUserBaseDn());
env.put(Context.SECURITY_PRINCIPAL, userDnAndNamespace[0] + "," + options.getUserBaseDn());
env.put(Context.SECURITY_CREDENTIALS, password);
logger.debug("Binding the user.");
context = new InitialDirContext(env);
logger.debug("User " + user + " successfully bound.");
context.close();
} catch (Exception e) {
logger.warn("User " + user + " authentication failed.", e);
throw new LoginException("Authentication failed: " + e.getMessage());
} finally {
if (context != null) {
try {
context.close();
} catch (Exception e) {
// ignore
}
}
}
principals.add(new UserPrincipal(user));
// step 3: retrieving user roles
try {
String[] roles = cache.getUserRoles(user, userDnAndNamespace[0], userDnAndNamespace[1]);
for (String role : roles) {
principals.add(new RolePrincipal(role));
}
} catch (Exception e) {
throw new LoginException("Can't get user " + user + " roles: " + e.getMessage());
}
return true;
}
use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project karaf by apache.
the class KarafJaasAuthenticator method assertRolePresent.
private void assertRolePresent(Subject subject) throws FailedLoginException {
boolean hasCorrectRole = role == null || role.isEmpty();
int roleCount = 0;
for (Principal principal : subject.getPrincipals()) {
if (principal instanceof RolePrincipal) {
if (!hasCorrectRole) {
hasCorrectRole = role.equals(principal.getName());
}
roleCount++;
}
}
if (roleCount == 0) {
throw new FailedLoginException("User doesn't have role defined");
}
if (!hasCorrectRole) {
throw new FailedLoginException("User doesn't have the required role " + role);
}
}
use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project karaf by apache.
the class GuardProxyCatalogTest method testInvocationBlocking1.
@SuppressWarnings("unchecked")
@Test
public void testInvocationBlocking1() throws Exception {
Dictionary<String, Object> c1 = new Hashtable<>();
c1.put(Constants.SERVICE_PID, "foobar");
c1.put("service.guard", "(objectClass=" + TestServiceAPI.class.getName() + ")");
c1.put("doit", "a,b");
Dictionary<String, Object> c2 = new Hashtable<>();
c2.put(Constants.SERVICE_PID, "barfoobar");
c2.put("service.guard", "(objectClass=" + TestObjectWithoutInterface.class.getName() + ")");
c2.put("compute", "c");
BundleContext bc = mockConfigAdminBundleContext(c1, c2);
final Object proxy = testCreateProxy(bc, new Class[] { TestServiceAPI.class, TestObjectWithoutInterface.class }, new CombinedTestService());
// Run with the right credentials so we can test the expected roles
Subject subject = new Subject();
subject.getPrincipals().add(new RolePrincipal("b"));
Subject.doAs(subject, (PrivilegedAction<Object>) () -> {
assertEquals("Doing it", ((TestServiceAPI) proxy).doit());
if (!runningUnderCoverage) {
try {
((TestObjectWithoutInterface) proxy).compute(44L);
fail("Should have been blocked");
} catch (SecurityException se) {
// good
}
}
return null;
});
}
use of org.apache.karaf.jaas.boot.principal.RolePrincipal in project karaf by apache.
the class GuardProxyCatalogTest method testInvocationBlocking2.
@SuppressWarnings("unchecked")
@Test
public void testInvocationBlocking2() throws Exception {
Dictionary<String, Object> config = new Hashtable<>();
config.put(Constants.SERVICE_PID, "barfoobar");
config.put("service.guard", "(objectClass=" + TestObjectWithoutInterface.class.getName() + ")");
config.put("compute(long)[\"42\"]", "b");
config.put("compute(long)", "c");
BundleContext bc = mockConfigAdminBundleContext(config);
final Object proxy = testCreateProxy(bc, new Class[] { TestServiceAPI.class, TestObjectWithoutInterface.class }, new CombinedTestService());
// Run with the right credentials so we can test the expected roles
Subject subject = new Subject();
subject.getPrincipals().add(new RolePrincipal("b"));
Subject.doAs(subject, (PrivilegedAction<Object>) () -> {
if (!runningUnderCoverage) {
assertEquals(-42L, ((TestObjectWithoutInterface) proxy).compute(42L));
try {
((TestObjectWithoutInterface) proxy).compute(44L);
fail("Should have been blocked");
} catch (SecurityException se) {
// good
}
}
return null;
});
}
Aggregations