How to get all permissions defined in Keycloak's client - keycloak

How can I retrieve all permissions defined in client using keycloak-admin-client library in Java. For example:
Keycloak keycloak = Keycloak.getInstance(keyCloakUrl, keyCloakRealm, keyCloakClientId, token);
// I can get all resources like this:
List<ResourceRepresentation> resources = keycloak.realm(realm).clients().get(keyCloakClientId).authorization().resources().resources();
// I can get all policies like this:
List<PolicyRepresentation> policies = keycloak.realm(realm).clients().get(keyCloakClientId).authorization().policies().policies();
// So I would expect something like this to work for permissions:
List<ResourcePermissionRepresentation> permissions = keycloak.realm(realm).clients().get(keyCloakClientId).authorization().permissions().permissions();
// But there is no such method

Related

JWT Auth with Servicestack Ormlite - Generated Bearer token too large to use (>4096)

I'm migrating my ServiceStack Ormite MVC application to use the JWTAuthProvider for stateless auth. I have this working by authenticating as normal, and setting the returned BearerToken and RefreshToken on a successful auth:
using (var authService = HostContext.ResolveService<AuthenticateService>(ServiceStackRequest))
{
var response = await authService.PostAsync(new Authenticate
{
provider = CredentialsAuthProvider.Name,
UserName = model.UserName,
Password = model.Password,
RememberMe = true,
});
var authResponse = response.GetDto() as AuthenticateResponse;
Response.Cookies.Append("ss-tok", authResponse.BearerToken, new CookieOptions() {...});
Response.Cookies.Append("ss-reftok", authResponse.RefreshToken, new CookieOptions() {...});
}
This appears to work for some users and not for others. The problem seems to be that user accounts with a lot of permissions end up with much larger BearerToken values, some over 4096, so these cannot be set for the ss-tok cookie.
The JWT Auth provider docs provide references to the CreatePayloadFilter and the PopulateSessionFilter, however these are only used when creating a session from a token, not the other way around. I want to filter out items (the permissions in particular) when serializing to a token.
Ideally the permissions would be excluded if there are too many (or always be excluded if that's not possible) and would be lazy-loaded when accessed. This may be possible with a custom AuthUserSession inheriting from the base AuthUserSession that Lazy-loads the Permissions, but I don't know how I could do this without the JWT Provider loading the permissions to serialise too.

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

Correct configuration for REST endpoints in Shiro

My original post is here
I am trying to protect a set of REST endpoints with Shiro. My theory is that if I pass a JWT with my REST request, that I can use Shiro (via annotations) to secure my endpoints.
I've create my endpoints like this (for example):
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("status/{companyId}")
#RequiresAuthentication
#RequiresRoles("SomeRole")
public Response getStatus(#PathParam("companyId") int companyId){
... do stuff ...
}
I'm expecting that if I call the endpoint without authenticating, I will get a HTTP 401 error. However, the method is called successfully if the JWT is not supplied as it would be when there is no security on it at all.
I assume then that my Shiro config is incorrect. Since this is strictly a 'backend' application, I have no use for the Shiro/Stormpath configurations that apply to anything 'front-end' related (such as loginURLs, etc.)
Here is my shiro.ini :
[main]
#ERRORS IF UNCOMMENTED
#cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager
#securityManager.cacheManager = $cacheManager
#stormpathClient.cacheManager = $cacheManager
# NOT NEEDED?
#sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
#securityManager.sessionManager = $sessionManager
#securityManager.sessionManager.sessionIdCookieEnabled = false
#securityManager.sessionManager.sessionIdUrlRewritingEnabled = false
[urls]
/** = rest
This configuration lets every request through (as described above).
If I uncomment the [main] section, I get IllegalArgumentException: Configuration error. Specified object [stormpathClient] with property [cacheManager] without first defining that object's class. Please first specify the class property first, e.g. myObject = fully_qualified_class_name and then define additional properties.
What I need to figure out is what is the correct minimum Shiro configuration for REST endpoints (and ONLY REST endpoints) so I can allow access with a JWT.
Thanks for any help.
I'm guessing the annotations are not being processed by anything at runtime. You will need to tell your JAX-RS app to process them.
I've done this with this lib in the past:
https://github.com/silb/shiro-jersey/
Specifically something like this:
https://github.com/silb/shiro-jersey/blob/master/src/main/java/org/secnod/shiro/jersey/AuthorizationFilterFeature.java
As for the second part of the problem, my only guess is Stormpath/Shiro environment is not setup correctly.
Did you put filter config in your web.xml or is all of the config loaded from the servlet fragment?

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.