Keycloak ignores realmRoles when adding a user by rest api - keycloak

When I am creating a new user by using Keycloak rest API, the application ignores the realmRoles property not assigning the role to the new user.
Here is an exemple
POST: https://localhost:8543/auth/admin/realms/quarkus/users
Body:
{
"username":"alexandre",
"enabled":true,
"emailVerified":true,
"firstName":"Alexandre",
"lastName":"Oliveira",
"email":"alexandreqogmailcom",
"credentials":[
{
"type":"password",
"value":"123456",
"temporary":false
}
],
"realmRoles":[
"user_esc"
],
"access":{
"mapRoles":true
}
Is there a way to resolve this problem or a work around ?
PS: I am using the keycloak version 12.0.1

If you are expecting that with the endpoint:
POST: https://localhost:8543/auth/admin/realms/quarkus/users
it will also create the realm roles, that will not happen, it will not create the Realm roles. To create the Realm roles you either use the Admin Console or you use the endpoint:
POST https://localhost:8543/auth/admin/realms/quarkus/roles
with the payload
{"name":"<ROLE_NAME>","description":"<DESCRIPTION>"}
if it is a non Composite Realm Role.
To assign the Realm Role to the user, after having create the user, call the endpoint:
POST: https://localhost:8543/auth/admin/realms/quarkus/users/<USER_ID>/role-mappings/realm
with the payload
[{"id":"<Role ID>","name":"<Role Name>"}]
The role ID you can get it from:
GET: https://localhost:8543/auth/admin/realms/quarkus/roles/<ROLE_NAME>
and the user ID from :
GET: https://localhost:8543/auth/admin/realms/quarkus/users/?username=<USERNAME>
I have upload the following bash scripts to automatize this process.

Related

return claim without requiring role quarkus

I have a keycloak + quarkus setup running in docker compose but I'm running into a strange issue.
Authentication and authorization works fine but when I return the username it is empty unless I require a role.
In other words, when my endpoint requires a role everything works fine and I get the users username returned in the response, however if I remove the rolesrequired annotation the response is empty.
Is it possible to get the username without a rolesrequired annotation somehow?
This works:
#GET
#Path('me')
#RolesRequired('user')
public User me() {
return new User(identity);
}
This doesn't work (it returns username: '')
#GET
#Path('me')
public User me() {
return new User(identity);
}
Quarkus OIDC extension does not handle authentication token for resouce method that not secured (with out #RolesAllowed annotation) and User Identity is anonymous
Use #Authenticated instead #RolesAllowed annotation for methods when you want to get UserIdentity.

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}"
}

IdenityServer3 windows auth support and custom grant flow support

I am looking for IdentityServer3 version which can support windows authentication and customgrant.
I found the windows authentication version: "Windows Auth All-in-One" in github.
Windows token conversion is working fine.
But when I try to use custom grant flow, using the following code:
var client = new TokenClient(
Constants.TokenEndpoint,
"customclient",
"secret");
return client.RequestCustomGrantAsync("custom", "read write", ParameterData).Result;
I am getting the response as:
"error": "unsupported_grant_type"
Any idea how to enable the custom grant type in Windows Auth All-in-One version of Identity server?
Using IdentityServer's extensibility mechanism, you can register a custom grant validator for the my_custom_credential.
The job of a custom grant validator is to validate the incoming data, and map that to an IdentityServer user.
You start by implementing this interface:
public interface ICustomGrantValidator
{
Task<CustomGrantValidationResult> ValidateAsync(ValidatedTokenRequest request);
string GrantType { get; }
}
In the GrantType property you specify which custom grant type you want to handle with this validator.
In the ValidateAsync method you have access to the raw requests (e.g. for reading custom parameters like in the example
above) as well as validated data like scopes and client identity.
The result object allows you to set either a principal (with claims) that map to a user - or an error message.
You register the validator by setting it on the service factory:
factory.CustomGrantValidators.Add(
new Registration<ICustomGrantValidator, MyCustomGrantValidator>());
To use this grant type, you need to create a client with the following configuration:
The Flow must be set to Custom
The AllowedCustomGrantTypes must include the custom grant type
https://identityserver.github.io/Documentation/docsv2/advanced/customGrantTypes.html

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.