Java Code Examples for org.keycloak.representations.AccessToken#Access
The following examples show how to use
org.keycloak.representations.AccessToken#Access .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UserClientRoleMappingMapper.java From keycloak-protocol-cas with Apache License 2.0 | 6 votes |
@Override public void setAttribute(Map<String, Object> attributes, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession session, ClientSessionContext clientSessionCtx) { String clientId = mappingModel.getConfig().get(ProtocolMapperUtils.USER_MODEL_CLIENT_ROLE_MAPPING_CLIENT_ID); String rolePrefix = mappingModel.getConfig().get(ProtocolMapperUtils.USER_MODEL_CLIENT_ROLE_MAPPING_ROLE_PREFIX); if (clientId != null && !clientId.isEmpty()) { AccessToken.Access access = RoleResolveUtil.getResolvedClientRoles(session, clientSessionCtx, clientId, false); if (access == null) { return; } setAttribute(attributes, mappingModel, access.getRoles(), rolePrefix); } else { // If clientId is not specified, we consider all clients Map<String, AccessToken.Access> allAccess = RoleResolveUtil.getAllResolvedClientRoles(session, clientSessionCtx); Set<String> allRoles = allAccess.values().stream().filter(Objects::nonNull) .flatMap(access -> access.getRoles().stream()) .collect(Collectors.toSet()); setAttribute(attributes, mappingModel, allRoles, rolePrefix); } }
Example 2
Source File: ArticleController.java From spring-cloud-yes with Apache License 2.0 | 6 votes |
@GetMapping("") public PageInfo<Article> search( Principal principal, @RequestParam(required = false) String keyword, PageVoWithSort4Mybatis pageVo ) { if (principal instanceof KeycloakPrincipal) { AccessToken accessToken = ((KeycloakPrincipal) principal).getKeycloakSecurityContext().getToken(); String preferredUsername = accessToken.getPreferredUsername(); AccessToken.Access realmAccess = accessToken.getRealmAccess(); Set<String> roles = realmAccess.getRoles(); log.info("当前登录用户:{}, 角色:{}", preferredUsername, roles); } PageHelper.startPage(pageVo.getPage(), pageVo.getRows(), pageVo.getSort()); if (StringUtils.isEmpty(keyword)) { return new PageInfo<>( this.articleMapper.selectAll() ); } return new PageInfo<>( this.articleMapper.searchByCondition(keyword) ); }
Example 3
Source File: AudienceResolveProtocolMapper.java From keycloak with Apache License 2.0 | 6 votes |
@Override public AccessToken transformAccessToken(AccessToken token, ProtocolMapperModel mappingModel, KeycloakSession session, UserSessionModel userSession, ClientSessionContext clientSessionCtx) { String clientId = clientSessionCtx.getClientSession().getClient().getClientId(); for (Map.Entry<String, AccessToken.Access> entry : RoleResolveUtil.getAllResolvedClientRoles(session, clientSessionCtx).entrySet()) { // Don't add client itself to the audience if (entry.getKey().equals(clientId)) { continue; } AccessToken.Access access = entry.getValue(); if (access != null && access.getRoles() != null && !access.getRoles().isEmpty()) { token.addAudience(entry.getKey()); } } return token; }
Example 4
Source File: RoleResolveUtil.java From keycloak with Apache License 2.0 | 6 votes |
private static void addToToken(AccessToken token, RoleModel role) { AccessToken.Access access = null; if (role.getContainer() instanceof RealmModel) { access = token.getRealmAccess(); if (token.getRealmAccess() == null) { access = new AccessToken.Access(); token.setRealmAccess(access); } else if (token.getRealmAccess().getRoles() != null && token.getRealmAccess().isUserInRole(role.getName())) return; } else { ClientModel app = (ClientModel) role.getContainer(); access = token.getResourceAccess(app.getClientId()); if (access == null) { access = token.addAccess(app.getClientId()); if (app.isSurrogateAuthRequired()) access.verifyCaller(true); } else if (access.isUserInRole(role.getName())) return; } access.addRole(role.getName()); }
Example 5
Source File: SkeletonKeyTokenTest.java From keycloak with Apache License 2.0 | 5 votes |
@Test public void testToken() throws Exception { AccessToken token = createSimpleToken(); String json = JsonSerialization.writeValueAsString(token); token = JsonSerialization.readValue(json, AccessToken.class); Assert.assertEquals("111", token.getId()); AccessToken.Access foo = token.getResourceAccess("foo"); Assert.assertNotNull(foo); Assert.assertTrue(foo.isUserInRole("admin")); }
Example 6
Source File: Auth.java From keycloak with Apache License 2.0 | 5 votes |
public boolean hasClientRole(ClientModel app, String role) { if (cookie) { return user.hasRole(app.getRole(role)); } else { AccessToken.Access access = token.getResourceAccess(app.getClientId()); return access != null && access.isUserInRole(role); } }
Example 7
Source File: Auth.java From keycloak with Apache License 2.0 | 5 votes |
public boolean hasRealmRole(String role) { if (cookie) { return user.hasRole(realm.getRole(role)); } else { AccessToken.Access access = token.getRealmAccess(); return access != null && access.isUserInRole(role); } }
Example 8
Source File: AdminAuth.java From keycloak with Apache License 2.0 | 5 votes |
public boolean hasAppRole(ClientModel app, String role) { if (client instanceof ClientModel) { RoleModel roleModel = app.getRole(role); if (roleModel == null) return false; return user.hasRole(roleModel) && client.hasScope(roleModel); } else { AccessToken.Access access = token.getResourceAccess(app.getClientId()); return access != null && access.isUserInRole(role); } }
Example 9
Source File: AdminAuth.java From keycloak with Apache License 2.0 | 5 votes |
public boolean hasRealmRole(String role) { if (client instanceof ClientModel) { RoleModel roleModel = realm.getRole(role); if (roleModel == null) return false; return user.hasRole(roleModel) && client.hasScope(roleModel); } else { AccessToken.Access access = token.getRealmAccess(); return access != null && access.isUserInRole(role); } }
Example 10
Source File: RoleResolveUtil.java From keycloak with Apache License 2.0 | 5 votes |
/** * Object (possibly null) containing all the user's realm roles. Including user's groups roles. Composite roles are expanded. * Just the roles, which current client has role-scope-mapping for (or it's clientScopes) are included. * Current client means the client corresponding to specified clientSessionCtx. * * @param session * @param clientSessionCtx * @param createIfMissing * @return can return null (just in case that createIfMissing is false) */ public static AccessToken.Access getResolvedRealmRoles(KeycloakSession session, ClientSessionContext clientSessionCtx, boolean createIfMissing) { AccessToken rolesToken = getAndCacheResolvedRoles(session, clientSessionCtx); AccessToken.Access access = rolesToken.getRealmAccess(); if (access == null && createIfMissing) { access = new AccessToken.Access(); rolesToken.setRealmAccess(access); } return access; }
Example 11
Source File: UserRealmRoleMappingMapper.java From keycloak with Apache License 2.0 | 5 votes |
@Override protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession session, ClientSessionContext clientSessionCtx) { String rolePrefix = mappingModel.getConfig().get(ProtocolMapperUtils.USER_MODEL_REALM_ROLE_MAPPING_ROLE_PREFIX); AccessToken.Access access = RoleResolveUtil.getResolvedRealmRoles(session, clientSessionCtx, false); if (access == null) { return; } AbstractUserRoleMappingMapper.setClaim(token, mappingModel, access.getRoles(),null, rolePrefix); }
Example 12
Source File: AbstractUserRoleMappingMapper.java From keycloak with Apache License 2.0 | 5 votes |
private static boolean checkAccessToken(IDToken idToken, List<String> path, Object attributeValue) { if (!(idToken instanceof AccessToken)) { return false; } if (!(attributeValue instanceof Collection)) { return false; } Collection<String> roles = (Collection<String>) attributeValue; AccessToken token = (AccessToken) idToken; AccessToken.Access access = null; if (path.size() == 2 && "realm_access".equals(path.get(0)) && "roles".equals(path.get(1))) { access = token.getRealmAccess(); if (access == null) { access = new AccessToken.Access(); token.setRealmAccess(access); } } else if (path.size() == 3 && "resource_access".equals(path.get(0)) && "roles".equals(path.get(2))) { String clientId = path.get(1); access = token.addAccess(clientId); } else { return false; } for (String role : roles) { access.addRole(role); } return true; }
Example 13
Source File: AbstractUser.java From keycloak-dropwizard-integration with Apache License 2.0 | 5 votes |
private Set<String> selectRealmRoles() { Set<String> roles = new HashSet<>(); AccessToken.Access realmAccess = securityContext.getToken().getRealmAccess(); if (realmAccess != null && realmAccess.getRoles() != null) { roles.addAll(realmAccess.getRoles()); } return Collections.unmodifiableSet(roles); }
Example 14
Source File: AbstractUser.java From keycloak-dropwizard-integration with Apache License 2.0 | 5 votes |
private Set<String> selectResourceRoles(KeycloakResource keycloakResource) { Set<String> roles = new HashSet<>(); AccessToken.Access resourceAccess = securityContext.getToken().getResourceAccess(keycloakResource.getResource()); if (resourceAccess != null && resourceAccess.getRoles() != null) { roles.addAll(resourceAccess.getRoles()); } return Collections.unmodifiableSet(roles); }
Example 15
Source File: UserRealmRoleMappingMapper.java From keycloak-protocol-cas with Apache License 2.0 | 5 votes |
@Override public void setAttribute(Map<String, Object> attributes, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession session, ClientSessionContext clientSessionCtx) { String rolePrefix = mappingModel.getConfig().get(ProtocolMapperUtils.USER_MODEL_REALM_ROLE_MAPPING_ROLE_PREFIX); AccessToken.Access access = RoleResolveUtil.getResolvedRealmRoles(session, clientSessionCtx, false); if (access == null) { return; } setAttribute(attributes, mappingModel, access.getRoles(), rolePrefix); }
Example 16
Source File: OAuthGrantTest.java From keycloak with Apache License 2.0 | 4 votes |
@Test public void oauthGrantAcceptTest() { oauth.clientId(THIRD_PARTY_APP); oauth.doLoginGrant("test-user@localhost", "password"); grantPage.assertCurrent(); grantPage.assertGrants(OAuthGrantPage.PROFILE_CONSENT_TEXT, OAuthGrantPage.EMAIL_CONSENT_TEXT, OAuthGrantPage.ROLES_CONSENT_TEXT); grantPage.accept(); Assert.assertTrue(oauth.getCurrentQuery().containsKey(OAuth2Constants.CODE)); EventRepresentation loginEvent = events.expectLogin() .client(THIRD_PARTY_APP) .detail(Details.CONSENT, Details.CONSENT_VALUE_CONSENT_GRANTED) .assertEvent(); String codeId = loginEvent.getDetails().get(Details.CODE_ID); String sessionId = loginEvent.getSessionId(); OAuthClient.AccessTokenResponse accessToken = oauth.doAccessTokenRequest(oauth.getCurrentQuery().get(OAuth2Constants.CODE), "password"); String tokenString = accessToken.getAccessToken(); Assert.assertNotNull(tokenString); AccessToken token = oauth.verifyToken(tokenString); assertEquals(sessionId, token.getSessionState()); AccessToken.Access realmAccess = token.getRealmAccess(); assertEquals(1, realmAccess.getRoles().size()); Assert.assertTrue(realmAccess.isUserInRole("user")); Map<String, AccessToken.Access> resourceAccess = token.getResourceAccess(); assertEquals(1, resourceAccess.size()); assertEquals(1, resourceAccess.get("test-app").getRoles().size()); Assert.assertTrue(resourceAccess.get("test-app").isUserInRole("customer-user")); events.expectCodeToToken(codeId, loginEvent.getSessionId()).client(THIRD_PARTY_APP).assertEvent(); accountAppsPage.open(); assertEquals(1, driver.findElements(By.id("revoke-third-party")).size()); accountAppsPage.revokeGrant(THIRD_PARTY_APP); events.expect(EventType.REVOKE_GRANT) .client("account").detail(Details.REVOKED_CLIENT, THIRD_PARTY_APP).assertEvent(); assertEquals(0, driver.findElements(By.id("revoke-third-party")).size()); }
Example 17
Source File: IdentityBrokerService.java From keycloak with Apache License 2.0 | 4 votes |
private boolean canReadBrokerToken(AccessToken token) { Map<String, AccessToken.Access> resourceAccess = token.getResourceAccess(); AccessToken.Access brokerRoles = resourceAccess == null ? null : resourceAccess.get(Constants.BROKER_SERVICE_CLIENT_ID); return brokerRoles != null && brokerRoles.isUserInRole(Constants.READ_TOKEN_ROLE); }
Example 18
Source File: KeycloakIdentity.java From keycloak with Apache License 2.0 | 4 votes |
public KeycloakIdentity(AccessToken accessToken, KeycloakSession keycloakSession) { if (accessToken == null) { throw new ErrorResponseException("invalid_bearer_token", "Could not obtain bearer access_token from request.", Status.FORBIDDEN); } if (keycloakSession == null) { throw new ErrorResponseException("no_keycloak_session", "No keycloak session", Status.FORBIDDEN); } this.accessToken = accessToken; this.keycloakSession = keycloakSession; this.realm = keycloakSession.getContext().getRealm(); Map<String, Collection<String>> attributes = new HashMap<>(); try { ObjectNode objectNode = JsonSerialization.createObjectNode(this.accessToken); Iterator<String> iterator = objectNode.fieldNames(); while (iterator.hasNext()) { String fieldName = iterator.next(); JsonNode fieldValue = objectNode.get(fieldName); List<String> values = new ArrayList<>(); if (fieldValue.isArray()) { Iterator<JsonNode> valueIterator = fieldValue.iterator(); while (valueIterator.hasNext()) { values.add(valueIterator.next().asText()); } } else { String value = fieldValue.asText(); if (StringUtil.isNullOrEmpty(value)) { continue; } values.add(value); } if (!values.isEmpty()) { attributes.put(fieldName, values); } } AccessToken.Access realmAccess = accessToken.getRealmAccess(); if (realmAccess != null) { attributes.put("kc.realm.roles", realmAccess.getRoles()); } Map<String, AccessToken.Access> resourceAccess = accessToken.getResourceAccess(); if (resourceAccess != null) { resourceAccess.forEach((clientId, access) -> attributes.put("kc.client." + clientId + ".roles", access.getRoles())); } ClientModel clientModel = getTargetClient(); UserModel clientUser = null; if (clientModel != null) { clientUser = this.keycloakSession.users().getServiceAccount(clientModel); } UserModel userSession = getUserFromSessionState(); this.resourceServer = clientUser != null && userSession.getId().equals(clientUser.getId()); if (resourceServer) { this.id = clientModel.getId(); } else { this.id = userSession.getId(); } } catch (Exception e) { throw new RuntimeException("Error while reading attributes from security token.", e); } this.attributes = Attributes.from(attributes); }
Example 19
Source File: RoleResolveUtil.java From keycloak with Apache License 2.0 | 3 votes |
/** * Object (possibly null) containing all the user's client roles of client specified by clientId. Including user's groups roles. * Composite roles are expanded. Just the roles, which current client has role-scope-mapping for (or it's clientScopes) are included. * Current client means the client corresponding to specified clientSessionCtx. * * @param session * @param clientSessionCtx * @param clientId * @param createIfMissing * @return can return null (just in case that createIfMissing is false) */ public static AccessToken.Access getResolvedClientRoles(KeycloakSession session, ClientSessionContext clientSessionCtx, String clientId, boolean createIfMissing) { AccessToken rolesToken = getAndCacheResolvedRoles(session, clientSessionCtx); AccessToken.Access access = rolesToken.getResourceAccess(clientId); if (access == null && createIfMissing) { access = rolesToken.addAccess(clientId); } return access; }
Example 20
Source File: RoleResolveUtil.java From keycloak with Apache License 2.0 | 2 votes |
/** * Object (but can be empty map) containing all the user's client roles of all clients. Including user's groups roles. Composite roles are expanded. * Just the roles, which current client has role-scope-mapping for (or it's clientScopes) are included. * Current client means the client corresponding to specified clientSessionCtx. * * @param session * @param clientSessionCtx * @return not-null object (can return empty map) */ public static Map<String, AccessToken.Access> getAllResolvedClientRoles(KeycloakSession session, ClientSessionContext clientSessionCtx) { return getAndCacheResolvedRoles(session, clientSessionCtx).getResourceAccess(); }