Getting user keycloak Not Found exception - keycloak

I can't get user groups like in samples.
Samples from:
Take a look at our testsuite. For example:
UserTest
GroupTest
Sample code from examples for receiving groups user is member of:
List<GroupRepresentation> membership = realm.users().get(user.getId()).groups();
My approach:
1. I create keycloak object for admin-cli client in myrealm realm:
this.keycloak = KeycloakBuilder.builder()
.serverUrl("http://localhost:18080/auth")
.realm("myrealm")
.username("admin")
.password("admin")
.clientId("admin-cli")
.resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build())
.build();
When I try to get user:
//this line works
final UserResource userr = this.keycloak.realms().realm("myrealm").users().get("admin");
//this two doesnt, in both result is javax.ws.rs.NotFoundException: HTTP 404 Not Found
final UserRepresentation ur = userr.toRepresentation();
final List<GroupRepresentation> groups = this.getRealm().users().get(user.getId()).groups();
In keycloak from admin-cli I created realm "myrealm" with 2 users and 2 groups
Every user is member of both groups. admin is one of this users and is member of this two groups.
Users I've created are in "myrealm" realm, "admin" is one of them.
I've olso tried to give all available roles from clients and realm but this changes nothing.
admin-cli I meant keycloak app on localhost
What am I missing?
Libs I am using:
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
import org.keycloak.admin.client.resource.RealmResource;
import org.keycloak.admin.client.resource.UserResource;
import org.keycloak.admin.client.resource.UsersResource;
import org.keycloak.representations.idm.GroupRepresentation;
import org.keycloak.representations.idm.UserRepresentation;

I just stumbled into the same problem as you. The problem was with the get method. Its argument is not a user name (admin), but a user identifier. Something like 494061c1-c8f3-44c9-8542-df895af81716 .
In my case I properly tried to pass the user ID, but I used token ID instead which is something completely different.

Related

how to set Internal/Subscriber role as default role to all authenticated users in WSO2 Api manager?

i am trying to give default role as Internal/Subscriber to all users.
i made changes in we made changes in file /_system/config/apimgt/applicationdata/tenant-conf.json and added role such as to Internal/creator,Internal/everyone,apimrole
"Name": "apim:subscribe",
"Roles": "admin,Internal/creator,Internal/everyone,apimrole,Internal/subscriber"
it gives me below error
org.wso2.carbon.apimgt.api.APIManagementException: Error while adding the subscriber
laxman#gmail.com#carbon.super#carbon.super
any help appreciated
New user creation takes place in the WSO2 API Manager in two ways.
Through the management console of the API Manager
Self signup
In 1st way you can assign roles when creating users.
For self signed-up users there already exists a handler to assign Internal/subscriber role to the new users who are having Internal/selfsignup role.
To assign role: Internal/subscriber to new users or existing role not assigned users we have below two options:
Option 1
If you wish to assign subscriber role to existing role not assigned users using Management Console, then you can go to roles listing page there:
There is an option: Assign Users in Actions column in role list relevant to Internal/subscriber role.
It will list all the users who have not assigned Internal/subscriber role and there are several options to select many users at once and assign the role.
Option 2
You can write a custom user operation event listener and add it as OSGI bundle.
In this case you can refer this WSO2 IS doc and write a event listener extending AbstractIdentityUserOperationEventListener.
This sample code worked for me:
public class SampleEventListener extends AbstractIdentityUserOperationEventListener {
private static final String EVENT_LISTENER_TYPE = "org.wso2.carbon.user.core.listener.UserOperationEventListener";
private static final String SUBSCRIBER_ROLE = "Internal/subscriber";
#Override
public boolean doPreAddUser(String userName, Object credential, String[] roleList, Map<String, String> claims,
String profile, UserStoreManager userStoreManager) throws UserStoreException {
List<String> roles = new ArrayList<>(Arrays.asList(roleList));
if (!roles.isEmpty() && !roles.contains(SUBSCRIBER_ROLE)) {
userStoreManager.updateRoleListOfUser(userName, new String[]{}, new String[] { SUBSCRIBER_ROLE });
}
return true;
}
This will add Internal/subscriber role to each newly adding user, if the user doesn't have that role in the process of adding new user.
Here it has mentioned multiple interfaces with which you can implement User Store Listeners.
For OSGI bundle creation and deployment process you can find this sample GitHub project. You can copy the built jar file to the directory <APIM_HOME>/repository/components/dropins/ by following the steps have been mentioned there. (Since WSO2 API Manager is also using WSO2 IS components you can follow the same steps mentioned in README with the API Manger as well)
You can go through this blog post to get complete idea about OSGI bundling.

How to use Azure AD Graph API to create a new AppRoleAssignment

I'm trying to figure out how to create a new appRoleAssignment using the Azure AD Graph API. (It appears that the newer Microsoft Graph does NOT support creating app role assignments just yet). I want to use the default role.
var assignment = new Dictionary<string, string>();
assignment["id"] = "00000000-0000-0000-0000-000000000000";
assignment["principalId"] = "user-guid";
assignment["resourceId"] = "service-principal-guid";
var url = "https://graph.windows.net/{tenant.onmicrosoft.com}/servicePrinciapls/{service-principal-guid}/appRoleAssignments";
I also tried posting to:
var url = "https://graph.windows.net/{tenant.onmicrosoft.com}/appRoleAssignments";
I'm POSTing the data in the hopes to create the assignment but it is giving a 404 error.
The assignment dictionary gets converted to JSON and posted.
In this answer we discussed the endpoint to GET app role assignments for a user. The same endpoint is the one you would POST to to create a new app role assignment:
POST https://graph.windows.net/{tenant-id}/users/{id}/appRoleAssignments?api-version=1.6
...
{
"principalId":"{user-object-id}",
"resourceId":"{service-principal-object-id}",
"id":"00000000-0000-0000-0000-000000000000"
}
(In the example above, we use 00000000-0000-0000-0000-000000000000 as the app role ID because we want to create a default assignment (i.e. "no role"). This would correspond to the id of an AppRole in the ServicePrincipal object if we wanted to assign the user to a specific app role.)
Instead of using the servicePrincipal collection, we need to use the user entity to create the appRoleAssignment for the users. Here is an example for your reference:
POST:https://graph.windows.net/{tenant}/users/{userObjectId}/appRoleAssignments?api-version=1.6
authorization: Bearer {access_token}
Content-Type: application/json
{
"id":"00000000-0000-0000-0000-000000000000",
"resourceId":"{servicePrincipId}",
"principalId":"{userObjectId}"
}

Apache Shiro Multirealm Authentication + find out which realm did the authentication

I have 2 possible realms to authenticate my users in my webapplication.
here are a few lines from my shiro.ini:
securityManager.realms = $ldapRealm, $saltedJdbcRealm
strategy = org.apache.shiro.authc.pam.FirstSuccessfulStrategy
securityManager.authenticator.authenticationStrategy = $strategy
Authentication works fine for both realms and the FirstSuccessfulStrategy works fine as well.
In my custom AuthenticationFilter within the executeLogin() method I have this code to do the login:
Subject currentUser = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
currentUser.login(token);
How can I now determine which realm was resposible for the authentication after the .login() method is executed?
If the user was authenticated via the LDAP Realm I would like to get some more information about the user from the LDAP.
Does anyone know how this can be done?
Subject subj = SecurityUtils.getSubject()
SimplePrincipalCollection spc = (SimplePrincipalCollection) subj.getPrincipals();
Set<String> realmNames = spc.getRealmNames();
The realmNames variable should contain one element, the realm that authenticated the user.
If your realm implementation is a standard one then the SimpleAuthenticationInfo created when the user is authenticated will have been created with the name of the realm that successfully authenticated the user.

MembershipReboot with IdentityServer v3

I am having trouble extracting UserAccount properties from MembershipReboot in conjunction with Thinktecture IdentityServer. I have both up and running using the Sample repo here: https://github.com/identityserver/IdentityServer3.MembershipReboot
When I request the "openid profile" scope in an Implicit Grant Flow, I am missing a lot of the user account fields such as "given_name, middle_name", etc from the id_token and response from the userinfo endpoint. I understand this is because they need to be assigned in the GetClaimsFromAccount function.
I can see the requestedClaims come into the GetProfileDataAsync() function in the MembershipRebootUserService class and if I hover over the instance of TAccount in GetClaimsFromAccount I can see the Firstname, Lastname, etc properties appearing in the CustomUser dynamic proxy but I can't for the life of me work out how to access them and copy them into the claims collection?
More Info:
I suspect the issue is with this line:
claims.AddRange(userAccountService.MapClaims(account));
It looks like this should be converting the user account properties into claims but I dont get any back.
The way I understand it works is you add an option to your Scope object to return all of the claims for a user. IncludeAllClaimsForUser is the key property.
e.g.
new Scope
{
Enabled = true,
Name = "roles",
Type = ScopeType.Identity,
IncludeAllClaimsForUser = true,
Claims = new List<ScopeClaim>
{
new ScopeClaim("role")
}
}
My request includes the role property as well. This pulled back all the claims for the user from MR for me. My example is with Implicit flow btw.

Apache Shiro: How would you manage Users?

I want to use Shiro on my next web project but I do not know a good (if not the best) strategy to manage users ([users] in shiro.ini).
Is it best to create Shiro user for every registered member?
Or create a single Shiro user then for every member just store it to some database and acces it via that Shiro user?
If you would go for #1, how would you manage/automate it? Most of the projects I worked on opted for #2.
Thanks
Configuring users in shiro.ini is not a good option for production environment. It can be used only if you have a small number of user accounts and you don't need to create or change accounts at runtime. It is mostly used for testing.
It is better for almost all projects to use some storage to keep all user accounts. It can be database or some external authentication engine, like ldap, cas or even oauth.
You can just use Stormpath as your user/group store. Drop in the Shiro integration and boom - instant user/group data store for Shiro-enabled applications with a full management UI and Java SDK.
It even helps automate things like 'forgot password' emails and account email verification. It's free for many usages too. You can see the Shiro sample app using Stormpath as an example.
Shiro provides multiple ways to configure users. Take a look at the possible Realm configurations here.
If none of these satisfy your needs, you could even write a custom Realm for your application, that can, say, pull user info from a NoSQL database, or get info from a SAML response, or use OAuth2. It's definitely not advisable to create any user details in shiro.ini in production. To give a notion of what custom realms might look like, here's an example where I created a SAML2 based user authc and authz: shiro-saml2.
PLease do not use only one user for everyone. Avoid this option.
Much better to use one user(account) per user.
In shiro, you can have the RDMS Realm that allows you to use a simple database like mysql in order to store your user /account / permissions. :)
Clone this project, (that is not mine), and get started in 1 minute! :)
shiro/mysql GIT example
Enjoy it :)
Shiro provide implementing your own realm as per your requirement.
Create a simple realm in which you can manage details, login, permissions and roles.
You can use jdbc, Hibernate, or any other authentication manner to manage them.
Configure this realm to your ini or whatever way you using in your project.
Now Shiro will automatically invoke methods of your realm class to look for credential, permissions, roles.
For ex I have a shiro hibernate realm I used my hibernate code to manage users in my db.
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
/**
* #author Ankit
*
*/
public class PortalHibernateRealm extends AuthorizingRealm {
private static final Logger LOGGER = new Logger(
PortalHibernateRealm.class.toString());
/**
*
*/
public PortalHibernateRealm() {
super();
/*
* Set credential matcher on object creation
*/
setCredentialsMatcher(new CredentialsMatcher() {
#Override
public boolean doCredentialsMatch(AuthenticationToken arg0,
AuthenticationInfo arg1) {
UsernamePasswordToken token = (UsernamePasswordToken) arg0;
String username = token.getUsername();
String password = new String(token.getPassword());
/*
Check for credential and return true if found valid else false
*/
return false;
}
});
}
#Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principalCollection) {
Collection<String> permissionSet;
SimpleAuthorizationInfo info = null;
Long userId = (Long) principalCollection.getPrimaryPrincipal();
//Using thi principle create SimpleAuthorizationInfo and provide permissions and roles
info = new SimpleAuthorizationInfo();
return info;
}
#Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken authcToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
/*using this token create a SimpleAuthenticationInfo like
User user = UserUtil.findByEmail(token.getUsername());
*/
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
primaryPrin, Password, screenName);
return authenticationInfo;
}
}