Make openam/opensso return role name instead of role universal id - authentication

I'm using OpenAM 9.5.2 for authenticating users on an application. The authentication works well but I'm having issues to get user memberships from final application.
I've defined the group "somegroup" in openam and added my user to this group. Now in my application, I want to test if authenticated users is member of this group. If I'm testing it with:
request.isUserInRole("somegroup");
I get false result. Actually, I have to test
request.isUserInRole("id=somegroup,ou=group,dc=opensso,dc=java,dc=net");
in order to get a true response.
I know that it's possible to define a privileged attribute mapping list in the sso agent configuration to map id=somegroup,ou=group,dc=opensso,dc=java,dc=net on somegroup, but it's not suitable in my situation since roles and groups are stored in an external database. It's not convenient to define role in database and mapping in sso agent conf.
So my question : is there a way to make openam use the "short" (i.e. somegroup) group name instead of its long universal id ?

This is not an answer, just one remark.
I've performed some researches in openam sources and it seems to confirm that the role name stored in repository is replaced by universalId when openam build the request. This is performed in com.sun.identity.idm.server.IdRepoJAXRPCObjectImpl.java class:
public Set getMemberships_idrepo(String token, String type, String name,
String membershipType, String amOrgName,
String amsdkDN
) throws RemoteException, IdRepoException, SSOException {
SSOToken ssoToken = getSSOToken(token);
Set results = new HashSet();
IdType idtype = IdUtils.getType(type);
IdType mtype = IdUtils.getType(membershipType);
Set idSet = idServices.getMemberships(ssoToken, idtype, name, mtype, amOrgName, amsdkDN);
if (idSet != null) {
Iterator it = idSet.iterator();
while (it.hasNext()) {
AMIdentity id = (AMIdentity) it.next();
results.add(IdUtils.getUniversalId(id));
}
}
return results;
}

To my knowledge this is not possible currently with out of box code. In case you have limited amount of groups, then privileged attribute mapping could be a way to go, but if not, then the issue gets more complicated.
You could try to change the AmRealm implementation (authenticateInternal method) to match your requirements and hook the new class into the container-specific ServiceResolver class (like http://sources.forgerock.org/browse/openam/trunk/opensso/products/j2eeagents/tomcat/v6/source/com/sun/identity/agents/tomcat/v6/AmTomcatAgentServiceResolver.java?r=700&r=700&r=700 )
You can also create a JIRA issue about providing a config property to put membership information into roles in non-UUID format.

Related

Keycloak retrieve custom attributes to KeycloakPrincipal

In my rest service i can obtain the principal information after authentication using
KeycloakPrincipal kcPrincipal = (KeycloakPrincipal) servletRequest.getUserPrincipal();
statement.
Keycloak principal doesn't contain all the information i need about the authenticated user.
Is it possible to customize my own principal type?
On the keycloak-server-end I've developed a user federation provider. I saw that UserModel makes possible to add a set of custom attributes to my user.
Is it possible to insert my custom principal in that code?
Is it possible to retrieve this attributes from keycloak principal?
What is the way?
To add custom attributes you need to do three things:
Add attributes to admin console
Add claim mapping
Access claims
The first one is explained pretty good here: https://www.keycloak.org/docs/latest/server_admin/index.html#user-attributes
Add claim mapping:
Open the admin console of your realm.
Go to Clients and open your client
This only works for Settings > Access Type confidential or public (not bearer-only)
Go to Mappers
Create a mapping from your attribute to json
Check "Add to ID token"
Access claims:
final Principal userPrincipal = httpRequest.getUserPrincipal();
if (userPrincipal instanceof KeycloakPrincipal) {
KeycloakPrincipal<KeycloakSecurityContext> kp = (KeycloakPrincipal<KeycloakSecurityContext>) userPrincipal;
IDToken token = kp.getKeycloakSecurityContext().getIdToken();
Map<String, Object> otherClaims = token.getOtherClaims();
if (otherClaims.containsKey("YOUR_CLAIM_KEY")) {
yourClaim = String.valueOf(otherClaims.get("YOUR_CLAIM_KEY"));
}
} else {
throw new RuntimeException(...);
}
I used this for a custom attribute I added with a custom theme.
Select Users > Lookup > click on ID > go to attributes tab > Add attribute > e.g.: phone > Save
Select Clients > click on Client ID > go to Mappers Tab > create mapper
Get custom attributes
UPDATE
Add 'phone' attribute on Group level, assign user to that group, and you get 'phone' attribute from group level for all users
Go back to mapper and update 'phone' with 'Aggregate attribute values = true' and 'Multivalued=true', and you get 'phone' as list with both attributes from group and user level. If you keep 'Aggregate attribute values = false' or 'Multivalued=false', you get just one value, where 'phone' attribute from user will override 'phone' attribute from group (which make sense)
For Keycloak > 18 the configuration of the mappers has moved in the UI:
Inside Clients > Your selected client under the tab Client Scopes, one has to select account-dedicated:
There custom mappers can be added:

Authentication in liferay pages

We are having a portlet on a liferay page. We want to put up up a permission on every action method that is performed. For example on page A we have landed an XYZ portlet. Now we want that whenever there is any action performed form this portlet, we want to check that if the user is having a role to perform this action or not.
It wont be a good approach to put up the code in Action method of the portlet cause we are having approximately 20 such pages and portlets.
Can we have some sort of filter or so, so that each action request is checked if the user is having the access to the content or not.
Thank you...
My idea.
Use a filter to intercept all request
You can add a filter to the Liferay Servlet to check every request.
For that you can use a hook-plugin.
Look at this :
http://www.liferay.com/fr/documentation/liferay-portal/6.1/development/-/ai/other-hooks
http://connect-sam.com/2012/06/creating-servlet-filter-hook-in-liferay-6-1-to-restrict-access-based-on-ip-location/
Issue with filter is that you can't access ThemeDisplay or use PortalUtil.getUser(request).
So you must use work around like that :
private User _getUser(HttpServletRequest request) throws Exception {
HttpSession session = request.getSession();
User user = PortalUtil.getUser(request);
if (user != null) {
return user;
}
String userIdString = (String) session.getAttribute("j_username");
String password = (String) session.getAttribute("j_password");
if ((userIdString != null) && (password != null)) {
long userId = GetterUtil.getLong(userIdString);
user = UserLocalServiceUtil.getUser(userId);
}
return user;
}
Filtering the request
To filter the request you must get :
page id (Layout id in Liferay)
portlet id
portlet lifecycle
One more time using a filter is a pain because you can get the ThemeDisplay. These params are easy to get (with real object instancee) with ThemeDisplay.
So you must get this as parameter in the request.
final String portletId = ParamUtil.get((HttpServletRequest) servletRequest, "p_p_id", "");
final String layoutId = ParamUtil.get((HttpServletRequest) servletRequest, "plid", "");
final String portletLifecycle = ParamUtil.get((HttpServletRequest) servletRequest, "p_p_lifecycle", "");
Lifecycle details :
portletLifecycle is a int and the meaning of value is :
0 : RENDER
1 : ACTION (the one that interests you)
2 : RESOURCE
I think that with this data you can be able to define if user can or cannot make the action.
You can get user roles from the user.
You can get the current page and portlet linked to the request.
And you can know if the request is an action request.
Good luck with Liferay.
You can add freely configurable permissions to Liferay, see the Developer Guide for detailed information. My first guess on this would be that these affect "model resources", e.g. the data that your portlet is dealing with, rather than portlet-resources, e.g. permissions on the individual portlet itself. Think of portlet-permissions as permissions that are defined by Liferay, model-resources as permissions where you can come up with your own vocabulary on the actions, e.g. "UPDATE_ADDRESS" etc.
These permissions will typically be tied to roles, which are granted to users/usergroups/etc.
Based on this variability, it depends on the nature of your permissions if you can write a filter to generically check permissions, or if it depends on more than the individual action call.
If you determine that there is a generic solution, look up PortletFilters, they behave just like ServletFilters. These can easily provide a home for permission checks.
It's quite hard to cover this topic in such a short answer, I hope to have given enough resources for you to continue your quest.
You can abuse some existing portlet permission like "Add to Page" and set it to roles that should call the action.
And by the rendering and action phases validate "has the user necessary permission".
Or you can create new permission and configure it by portlet-configuration. This way is cleaner, but difficulty.

typo3 extbase permissions in extensions

I have written one extension for making service order.
The issue I am facing here is,
There are FE users belong to three FE user groups namely "client", "Admin" and "Employee".
Here the client can make order and he should be able to see only his orders.
And the admin can see all orders done by different clients.
And the employee should be able to see only some clients orders.
Currently I made a order table with N:1 relation with FE user table. So every order should relate with any one client.
So in controller, I am checking the login user and using custom query in repository, I am accessing order related to loggedin client (FE user)
In file OrdersController.php
public function listAction() {
$orders = $this->ordersRepository->orderForLoginUsr();
$this->view->assign('orders', $orders);
}
In file OrdersRepository.php
public function orderForLoginUsr(){
$loggedInUserId = $GLOBALS ['TSFE']->fe_user->user['uid'];
$query = $this->createQuery();
$query->matching(
$query->equals('user', $loggedInUserId)
);
$query->setOrderings(array('crdate' => \TYPO3\CMS\Extbase\Persistence\QueryInterface::ORDER_DESCENDING));
return $query->execute();
}
But here my question is how to make admin user able to see all the orders done by all clients?
I have to write different template and action that calling function findAll() ?
$orders = $this->ordersRepository->findAll();
And how to set for usergroup Employee ?
Thanks in Advance
I think that the easiest way is to actually implement 3 actions with 3 different plugins, something like: listClientAction, listAdminAction and listEmployeeAction
In each of those action, you implement a method in your repository that fetch the right list of order with the good ordering:
orderForLoginClient(), orderForLoginEmployee(), orderForLoginAdmin()
What does the trick actually is that there will be 3 plugins on your page, one for each action. In each instance of your plugin, you set the access for the right be_group.
Don't forget to add the actions and plugin in the localconf and ext_table files.
I hope it will help!
Olivier
If your view is almost the same for client, admin, employee you should simply add a method like getOrderWithPermissionsForUser($currentUser);
In the method itself you should check for the usergroup and call different queries on your Repo.
If your view is different from usergroup to usergroup, you should use different templates with partials for the same parts.
If the data of the views is the same, just change the template for each usergroup in the action. If not use different actions.
Here is a helper method for easily changing your templatefile.
/**
* This method can change the used template file in an action method.
*
* #param string $templateName Something like "List" or "Foldername/Actionname".
* #param string $templateExtension Default is "html", but for other output types this may be changed as well.
* #param string $controllerName Optionally uses another subfolder of the Templates/ directory
* By default, the current controller name is used. Example value: "JobOffer"
* #param \TYPO3\CMS\Fluid\View\AbstractTemplateView $viewObject The view to set this template to. Default is $this->view
*/
protected function changeTemplateFile($templateName, $templateExtension = 'html', $controllerName = null, AbstractTemplateView $viewObject = null)
{
if (is_null($viewObject)) {
$viewObject = $this->view;
}
if (is_null($controllerName)) {
$controllerName = $this->getControllerContext()->getRequest()->getControllerName();
}
$templatePathAndFilename = $this->getTemplateRootpathForView($controllerName . '/' . $templateName . '.' . $templateExtension);
$viewObject->setTemplatePathAndFilename($templatePathAndFilename);
}

LINQ-to-SQL repository pattern attempt that is working, but am concerned with seperation

I am new to LINQ to SQL and the repository pattern and was attempting to do a simple example to get an understanding of how exactly my application should be structured. On my User model object I have a method called create(). When a user is created I want to insert into my User table and insert into my user_role table to assign the user the lowest possible role. I have a method on User model called create which does all this work. Shown below. Am I on the right path with how the repository pattern with LINQ to SQL should work.
public Boolean Create()
{
UserDbDataContext context = new UserDbDataContext();
// Create user.
IUserRepository userRepo = new UserRepository(context);
userRepo.Create(this);
// Get role that user should be added to.
IRoleRepository roleRepo = new RoleRepository(context);
var role = roleRepo.GetByRoleName("rookie");
// Insert user into role.
IUserRoleRepository userRoleRepo = new UserRoleRepository(context);
User_Role userRole = new User_Role();
userRole.RoleId = role.Id;
userRole.UserId = this.Id;
userRoleRepo.Create(userRole);
context.Dispose();
return true;
}
This is my controller method.
public ActionResult Register(string username, string password, string email)
{
User user = new User();
user.Username = username;
user.Password = password;
user.Email = email;
user.DateCreated = DateTime.Now;
user.Create();
return RedirectToAction("Test");
}
Is there a better approach I could take to improve the process? Any help would be vastly appreciated.
One of the main problems in your current approach is that the repositories individually have the responsibility to create/update the entities they hold on the database - This means that if you have changes in one repository and update another repository (i.e. your Create() call) both will be committed to the DB.
The usual way to structure this is having a unit of work (i.e. see here) that sits on top of all repositories that is responsible to commit changes to the DB, this structure also allows for transactions spanning multiple repositories.
I would say you should probably keep the responsibility of the repository to be saving and retrieving data for the entity. The "role" is a bit more on the "business logic" side and I would put that one layer up in a Service so you don't do any business logic responsibilities in the repository. For example you could call it CreateNewUserService and it would take the new users from the repository and then add the role. You would call that directly from the controller passing those arguments that you are applying directly now.
That way if your business logic changes so that you want to intialize the user as something else or not at all, you don't have to rip up the repository as it can keep it's responsibility of providing the user. This keeps the separation of concerns to be more clear as well and helps with maintenance and testability of both the repository and the service.

"Domain Users" group is empty when I use DirectoryServices "member" property

I'm using the following code to get the members of a group on my domain:
Dim de As New DirectoryEntry("LDAP://" & GroupDN)
For Each user As String In CType(de.Properties("member"), IEnumerable)
GroupCollection.Add(Username, Username)
Next
My problem is that when GroupDN (the distinguishedname of the group) is "CN=Domain Users,CN=Users,DC=Mydomain,DC=local", the For...Each loop doesn't execute, and when I check the Properties statement manually, it's got a count of zero. This seems to work for every other group in my domain, but the "Domain Users" group should contain everybody, and it appears to contain nobody.
I've checked, and the group lists everybody correctly in my Windows AD tools. Is there something obvious that I'm missing here? On a side note, is there a better way to get all the members of a group?
Unless you change the primary group id of a user, the user is not stored in the member attribute of the Domain Users group, rather it uses the fact that the primary group id is set to the Domain Users RID to determine membership in Domain Users. The normal case is that the Domain Users member attribute is empty; it would require that you make some changes to the default Active Directory implementation for this to not be the case.
The Domain Users group uses a
"computed" mechanism based on the
"primary group ID" of the user to
determine membership and does not
typically store members as
multi-valued linked attributes. If the
primary group of the user is changed,
their membership in the Domain Users
group is written to the linked
attribute for the group and is no
longer calculated. This was true for
Windows 2000 and has not changed for
Windows Server 2003.
Reference
The accepted answer is absolutely correct. By default every (user) object has 513 set in the property primarygroupid, which is the fixed "tail" of the Domain Users sid. But: this can be changed and every other group can be configured there, so we can't rely on that.
Here is an example method how to get the group members anyway (regardless if the default is kept or changed). I call a method like this after any query for members of active directory groups. In this example I get an array of distinguished names as result. But all other properties are possible, just add them to dSearcher.PropertiesToLoad.Add(...) and modify the result.
I know, this is a question about VB, I hope its easy to port it.
using System.DirectoryServices;
using System.Security.Principal;
public static string[] GetMembersDnByPrimaryGroupId(string domainName, SecurityIdentifier sidOfGroupToGetMembersByPrimaryGroupId)
{
// In a single domain environement the domain name is probably not needed, but
// we expect a multy domain environement
if (string.IsNullOrWhiteSpace(domainName) || sidOfGroupToGetMembersByPrimaryGroupId == null)
{
throw new ArgumentNullException($"Neither domainName nor sid may be null / blank: DomainName: { domainName }; sid: { sidOfGroupToGetMembersByPrimaryGroupId }");
//<----------
}
List<string> membersDnResult = new List<string>();
// Get the last segment of the group sid, this is what is stored in the "primaryGroupId"
string groupSidTail = sidOfGroupToGetMembersByPrimaryGroupId.Value.Split('-').Last();
string path = $"LDAP://{ domainName }";
DirectoryEntry dEntry = new DirectoryEntry(path);
SearchResultCollection adSearchResult = null;
DirectorySearcher dSearcher = new DirectorySearcher(dEntry);
// For this example we need just the distinguished name but you can add
// here the property / properties you want
dSearcher.PropertiesToLoad.Add("distinguishedName");
// set the filter to primarygroupid
dSearcher.Filter = $"(&(primarygroupid={ groupSidTail }))";
// May die thousand deaths, therefore exception handling is needed.
// My exception handling is outside of this method, you may want
// to add it here
adSearchResult = dSearcher.FindAll();
// Get the domains sid and check if the domain part of the wanted sid
// fits the domain sid (necesarry in multy domain environments)
byte[] domainSidBytes = (byte[])dEntry.Properties["objectSid"].Value;
SecurityIdentifier domainSid = new SecurityIdentifier(domainSidBytes, 0);
if (sidOfGroupToGetMembersByPrimaryGroupId.AccountDomainSid != domainSid)
{
throw new ArgumentException($"Domain sid of the wanted group { sidOfGroupToGetMembersByPrimaryGroupId.AccountDomainSid } does not fit the sid { domainSid } of the searched through domain \"{ domainName }\"");
//<----------
}
// We found entries by the primarygroupid
if (adSearchResult.Count > 0)
{
foreach (SearchResult forMemberByPrimaryGroupId in adSearchResult)
{
// Every AD object has a distinguishedName, therefore we acess "[0]"
// wihtout any further checking
string dn = forMemberByPrimaryGroupId.Properties["distinguishedName"][0].ToString();
membersDnResult.Add(dn);
}
}
return membersDnResult.ToArray();
}