How can I search for ldap fields when using ActiveDirectoryRealm in Apache Shiro? - apache

We use Apache Shiro to authenticate and authorize users using our active directory.
Authenticating the user and mapping groups works just fine using the following config:
adRealm = org.apache.shiro.realm.activedirectory.ActiveDirectoryRealm
adRealm.searchBase = "OU=MYORGANIZATION,DC=MYDOMAIN,DC=COM"
adRealm.groupRolesMap = "CN=SOMEREADGROUP":"read","CN=SOMEMODIFYGROUP":"modify","CN=SOMEADMINGROUP":"admin"
adRealm.url = ldaps://my.ad.url:636
adRealm.systemUsername= systemuser
adRealm.systemPassword= secret
adRealm.principalSuffix= #myorganization.mydomain.com
I can authenticate in Shiro using the following lines:
String user = "someuser";
String password = "somepassword";
Subject currentUser = SecurityUtils.getSubject ();
if (!currentUser.isAuthenticated ()){
UsernamePasswordToken token = new UsernamePasswordToken (user,
password);
token.setRememberMe (true);
currentUser.login (token);
}
We now want to get more user information from our ActiveDirectory. How can I do that using Apache Shiro? I was not able to find anything about it in the documentation.
In the source code of ActiveDirectoryRealm I found this line:
NamingEnumeration answer = ldapContext.search(searchBase, searchFilter, searchArguments, searchCtls);
So the first part of the answer is clear: use the ldapContext to search something in it. But how can I retrieve the LdapContext?

It depends on what you are trying to do. Are you just trying to reuse the context to run a query for something other then authentication or authorization? Or are you trying to change the behavior of the query in the AD realm?
If the latter, you would need to extend the ActiveDirectoryRealm and override the queryForAuthorizationInfo() method.
Are you implementing something that is custom for your environment?
(updated)
A couple things:
The realm has access to the LdapContext in the two touch points: queryForAuthenticationInfo() and queryForAuthorizationInfo(), so if you extend the AD realm or AbstractLdapRealm you should already have it. You could change the query to return other info and add the extra info to your Principal. Then you have access to that info directly from your Subject object.
Your realms, are not required to be singletons.
If you want to do some other sort of user management (email all users with a given role, create a user, etc). Then you could create a LdapContextFactory in your shiro.ini, and use the same instance for multiple objects.
[main]
...
ldapContextFactory = org.apache.shiro.realm.ldap.JndiLdapContextFactory
ldapContextFactory.systemUsername = foobar
ldapContextFactory.systemPassword = barfoo
adRealm = org.apache.shiro.realm.activedirectory.ActiveDirectoryRealm
adRealm.ldapContextFactory = $ldapContextFactory
...
myObject = com.biz.myco.MyObject
myObject.ldapContextFactory = $ldapContextFactory
This would work well if myObject is interacting with other Shiro components, (responding to events, etc), but less so if you need access to it from another framework. You could work around this by some sort of static initialization that builds creates the ldapContextFactory, but in my opinion, this is where the sweet spot of using the shiro.ini ends, and where using Guice or Spring shines.

Related

Create new user with new tenant in ABP Framework

I customized a new registration page in Blazor Wasm and want to create a new User with new Tenant. I wanted to use ITenantAppService.CreateAsync but it occurred permission problem.
var tenantDto = await _tenantAppService.CreateAsync(new TenantCreateDto()
{
Name = dto.UserName,
AdminEmailAddress = dto.EmailAddress,
AdminPassword = dto.Password,
});
Isn't it possible to create a Tenant by anonymous user?
I think I need to remove this permissions from tenantService or I need to give these permissions to anonymous user.
How can I create new tenant for new user?
I found solution.
Firstly, I tried to remove permissions but I didn't know how to remove easily. Then I tried firstly creating a user without tenant, then give him tenant.create permission but it didn't work.
Finally, I created a class
CustomTenantAppService : TenantManagementAppServiceBase, ITenantAppService
and implemented methods of ITenantAppService, so I could do everything that I want.

Keycloak - how to allow linking accounts without registration

I am managing a Keycloak realm with only a single, fully-trusted external IdP added that is intended to be the default authentication mechanism for users.
I do not want to allow user to register, i.e. I want to manually create a local Keycloak user, and that user should then be allowed to link his external IdP account to the pre-existing Keycloak account, having the email address as common identifier. Users with access to the external IdP but without an existing Keycloak account should not be allowed to connect.
I tried the following First Broker Login settings, but whenever a user tries to login, he gets an error message (code: invalid_user_credentials).
Do you have any idea what my mistake might be?
Looks like they integrated this feature in version 4.5.0.
See automatic account link docs.
Basically you need to create a new flow and add 2 alternative executions:
Create User If Unique
Automatically Link Brokered Account
According to the doc: https://www.keycloak.org/docs/latest/server_admin/index.html#detect-existing-user-first-login-flow, you must create a new flow like this:
et voilà :)
As per this discussion:
https://keycloak.discourse.group/t/link-idp-to-existing-user/1094/5
It’s a bug in keycloak and they seem to be a reluctant to fix it for
whatever reason. I have very few users so I solved it by manually
querying the idp for the information keycloak uses and then copying it
into the relevant fields in the UI. So there is no sign up process for
my users I just make them myself. Obviously that’s a poor solution
though, what we really need is someone to take over that PR and
persuade the maintainers to merge it.
This is the PR: https://github.com/keycloak/keycloak/pull/6282
As it is described in this GitHub issue response the solution is to use a JavaScript authenticator that handles this.
In order to do so, you need to do the folowing:
Enable [custom authenticators using JavaScript in your server[(https://www.keycloak.org/docs/latest/server_installation/#profiles) by https://stackoverflow.com/a/63274532/550222creating a file profile.properties in your configuration directory that contains the following:
feature.scripts=enabled
Create the custom authenticator. You have to create a JAR file (essentially a ZIP file) with the following structure:
META-INF/keycloak-scripts.json
auth-user-must-exist.js
The content of the files are in this Gist, but I am including them here as well:
META-INF/keycloak-scripts.json:
{
"authenticators": [
{
"name": "User must exists",
"fileName": "auth-user-must-exists.js",
"description": "User must exists"
}
]
}
auth-user-must-exist.js:
AuthenticationFlowError = Java.type("org.keycloak.authentication.AuthenticationFlowError")
ServicesLogger = Java.type("org.keycloak.services.ServicesLogger")
AbstractIdpAuthenticator = Java.type("org.keycloak.authentication.authenticators.broker.AbstractIdpAuthenticator")
IdpCreateUserIfUniqueAuthenticator = Java.type("org.keycloak.authentication.authenticators.broker.IdpCreateUserIfUniqueAuthenticator")
var IdpUserMustExists = Java.extend(IdpCreateUserIfUniqueAuthenticator)
function authenticate(context) {
var auth = new IdpUserMustExists() {
authenticateImpl: function(context, serializedCtx, brokerContext) {
var parent = Java.super(auth)
var session = context.getSession()
var realm = context.getRealm()
var authSession = context.getAuthenticationSession()
if (authSession.getAuthNote(AbstractIdpAuthenticator.EXISTING_USER_INFO) != null) {
context.attempted()
return
}
var username = parent.getUsername(context, serializedCtx, brokerContext)
if (username == null) {
ServicesLogger.LOGGER.resetFlow(realm.isRegistrationEmailAsUsername() ? "Email" : "Username")
authSession.setAuthNote(AbstractIdpAuthenticator.ENFORCE_UPDATE_PROFILE, "true")
context.resetFlow()
return
}
var duplication = parent.checkExistingUser(context, username, serializedCtx, brokerContext)
if (duplication == null) {
LOG.info("user not found " + username)
context.failure(AuthenticationFlowError.INVALID_USER)
return
} else {
authSession.setAuthNote(AbstractIdpAuthenticator.EXISTING_USER_INFO, duplication.serialize())
context.attempted()
}
}
}
auth.authenticate(context)
}
Then, you can define as follows:
User Must Exist -> ALTERNATIVE
Automatically Set Existing User -> ALTERNATIVE
Honestly i am surprised by the keycloak auto creating behavior. I tried to add new Authentication flow as descibed here https://www.keycloak.org/docs/latest/server_admin/index.html#automatically-link-existing-first-login-flow
My flow :
1 - Create User If Unique [ALTERNATIVE]
2 - Automatically Link Brokered Account [ALTERNATIVE]
My use case : Authenticating users from Github ( Github as IDP )
Result : when a github user logon with an existing "username" keycloak links the github account to my local user ( based on his username ). I expected using his email instead of username.

AccessDeniedException when writing into JCR (JackRabbit) [Magnolia]

I wrote a request filter for geoIP localization. It works the way that I request an external service for the localization and then write the information into JCR, into a dedicated workspace for caching/storage.
On the author instance this works, but on the public instance I constantly get a AccessDeniedException. I probably need to authenticate with the JCR, and I tried that too, using the crendentials from the magnolia.properties file:
magnolia.connection.jcr.userId = username
magnolia.connection.jcr.password = password
And this code for authentication:
Session session = MgnlContext.getJCRSession(WORKSPACE_IP_ADDRESSES);
session.impersonate(new SimpleCredentials("username", "password".toCharArray()));
I have the this xml to bootstrap the filter, and a FilterOrdering Task, configured as follows:
tasks.add(new FilterOrderingTask("geoIp", new String[] { "contentType", "login", "logout", "csrfSecurity",
"range", "cache", "virtualURI" }));
What am I missing?
What would be the proper to write into the JCR in Magnolia on the public instance?
Yeah, that could not work :D
Is your filter configured in Magnolia's filter chain or directly in web.xml? It needs to live in filter chain and it needs to be configured somewhere down the chain after the security filters so that user is already authenticated.
Then you can simply call MgnlContext.getJCRSession("workspace_name") to get access to repo and do whatever you need.
HTH,
Jan

RESTEasy support for JAX-RS #RolesAllowed

I've spend hours installing a custom login service in embedded Jetty 9.1.0.v20131115 and RESTEasy 3.0.5.Final. My login service will look users up in a database and assign them roles. It looks something like this:
final Constraint restConstraint = new Constraint();
restConstraint.setName(Constraint.__BASIC_AUTH);
restConstraint.setRoles(new String[]{"user", "admin");
restConstraint.setAuthenticate(true);
final ConstraintMapping restConstraintMapping = new ConstraintMapping();
restConstraintMapping.setConstraint(restConstraint);
restConstraintMapping.setPathSpec("/api/*");
final ConstraintSecurityHandler restSecurityHandler = new ConstraintSecurityHandler();
final LoginService myLoginService = new MyLoginService();
restSecurityHandler.setAuthenticator(new BasicAuthenticator());
restSecurityHandler.setRealmName(myLoginService.getName());
restSecurityHandler.addConstraintMapping(restConstraintMapping);
restSecurityHandler.setLoginService(myLoginService);
I have users joe-user who has the role of user, and jane-admin who has both user and admin roles. I have a REST GET resource named my-resource marked with:
#RolesAllowed("admin")
When I do an HTTP GET on my-resource, the browser correctly requests credentials, and I can login as either joe-user or jane-admin. The problem is that either user is allowed to GET my-resource!!
I've traced through some of the Jetty code, and indeed, as a result of my login service above, Jetty asks the login user which roles is supported. Unfortunately, Jetty will accept any of the roles I've specified in restConstraint.setRoles(new String[]{"user", "admin"), regardless of the user.
Apparently it is the RESTEasy layer that is supposed to recognize the #RolesAllowed("admin") annotation and validate the user. But how do I get RESTEasy to do that?
With a little help from the RESTEasy documentation, I found out that in order for RESTEasy to honor the #RolesAllowed annotations, one must turn on the resteasy.role.based.security context parameter switch in the web.xml file; or programatically, as I am doing:
final ServletHolder servletHolder = new ServletHolder(new HttpServlet30Dispatcher());
servletHolder.setInitParameter("javax.ws.rs.Application", MyApplication.class.getName());
servletHolder.setInitParameter("resteasy.role.based.security", String.valueOf(true));
contextHandler.addServlet(servletHolder, "/api/*");

Gerrit + LDAP = LDAP authentication unavailable Tuleap

I have been trying to setup gerrit to work with LDAP authentication. I read documentation numerous time some link do not work to the examples documentation pulled from tuleap on subject comes up with different solutions and explanations I have found three different configurations for ldap.inc from tuleap this is very confusing lacking explanation too.
So i am stuck with this problem. I have spent hours reading and trying to sort this out. Can someone tell me what am I doing wrong? here is my
ldap.inc
<?php
// LDAP server(s) to query for more information on Tuleap users and
// for authentication.
// You may use a comma-separated list if there are several servers available
// (leave blank to disable LDAP lookup).
// To specify secure LDAP servers, use 'ldaps://servername'
$sys_ldap_server = 'techhub.lt';
// To enable LDAP information on Tuleap users, also define the DN
// (distinguised name) to use in LDAP queries.
// The ldap filter is the filter to use to query the LDAP directory
// (%name% are substituted with the value from the user table)
$sys_ldap_dn = 'dc=techhub,dc=lt';
// For LDAP systems that do not accept anonymous binding, define here
// a valid DN and password:
$sys_ldap_bind_dn = "cn=admin,dc=techhub,dc=lt";
$sys_ldap_bind_passwd = "pass";
// LDAP authentication:
// Tuleap only supports authentication with a attempt to bind with LDAP server
// with a DN and a password.
// As the DN is usually long (eduid=1234,ou=people,dc=tuleap,dc=com) people
// usually authenticate themself with a login. So we need to first look
// for the DN that correspond to the given login and once found attempt to bind
// with the given password.
// In order to autenticate successfully users you need to properly
// User login (authentication 1st step)
$sys_ldap_uid = 'uid';
// User unique identifier. It's probably not the uid (or login) because it
// may change. This is a value that never change whatever happens to the
// user (even after deletion). It correspond to ldap_id field in user table
// in database.
// (authentication 2st step)
$sys_ldap_eduid = 'eduid';
// User common name
$sys_ldap_cn = 'cn';
// User email address
$sys_ldap_mail = 'mail';
// Specific DN to look for people
// You may use more than one DN separated by ; if you want to use several branches.
// Example : 'ou=People, dc=st, dc=com ; ou=Extranet, dc=st, dc=com'
$sys_ldap_people_dn = 'ou=people,dc=techhub,dc=lt';
// Filter used to look for user. It should cover a wide selection of
// fields because it's aim to find a user whatever it's given (email, name,
// login, etc).
$sys_ldap_search_user='(|(uid=%words%)(cn=%words%)(mail=%words%))';
// By default tooltip search is using ($sys_ldap_cn=%words%*) search filter (Hardcoded)
// You can change for a more sophisticated search
// $sys_ldap_tooltip_search_user='(&(|(sn=%words%*)(givenName=%words%*)(uid=%words%*))(!(givenName=BoiteVocale))(uid=*))';
// By default tooltip search attrs are $sys_ldap_cn and $sys_ldap_uid (Hardcoded)
// You can choose the attributes the search will retrieve
// $sys_ldap_tooltip_search_attrs='uid;sn;givenName';
// On account creation, what it the default user status (A, R, ...)
$sys_ldap_default_user_status = 'A';
// Enable LDAP based authentication for SVN by default for new projects
$sys_ldap_svn_auth = 1;
// Enable LDAP daily synchronization
$sys_ldap_daily_sync = 1;
// Enable usage of LDAP for people management. For instance autocompletion on
// user list, automatic creation of users not already referenced in the forge.
$sys_ldap_user_management = 1;
// Enable ldap group management.
// This allows to mirror a LDAP group defined in LDAP directory within the forge
// Doesn't work yet with only works with OpenLDAP compatible directories yet.
$sys_ldap_grp_enabled = 1;
// Specific DN where the user groups are
$sys_ldap_grp_dn = 'ou=groups,dc=techhub,dc=lt';
// Field that reprsent group name
$sys_ldap_grp_cn = 'cn';
// Field that indicate the membership of a user in a group
$sys_ldap_grp_member = 'uniquemember';
?>
AND gerrit.conf
[gerrit]
basePath = git
canonicalWebUrl = http://techhub.lt:2401/
[database]
type = H2
database = db/ReviewDB
[sendemail]
smtpServer = localhost
[container]
user = root
javaHome = /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.45.x86_64/jre
[sshd]
listenAddress = *:29418
[httpd]
listenUrl = http://*:2401/
[cache]
directory = cache
[auth]
type = LDAP
[ldap]
server = ldap://techhub.lt
accountBase = ou=people,dc=cro,dc=techhub,dc=lt
groupBase = ou=group,dc=cro,dc=techhub,dc=lt
accountFullName = cn
That's 2 different problems.
Do you manage to authenticate with LDAP accounts on gerrit ?
If yes, I think the problem comes from "$sys_ldap_eduid = 'eduid';" parameter in tuleap ldap config. This attribute should be the unique identifier of one's account in ldap (either you have such an attribute of you can use 'uid' as a fallback.