Java Code Examples for org.keycloak.representations.AccessToken#getRealmAccess()

The following examples show how to use org.keycloak.representations.AccessToken#getRealmAccess() . 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: ArticleController.java    From spring-cloud-yes with Apache License 2.0 6 votes vote down vote up
@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 2
Source File: KeycloakOauthPolicy.java    From apiman-plugins with Apache License 2.0 6 votes vote down vote up
private void forwardAuthRoles(IPolicyContext context, KeycloakOauthConfigBean config,
        AccessToken parsedToken) {

    if (config.getForwardRoles().getActive()) {
        Access access = null;

        if (config.getForwardRoles().getApplicationName() != null) {
            access = parsedToken.getResourceAccess(config.getForwardRoles().getApplicationName());
        } else {
            access = parsedToken.getRealmAccess();
        }

        if (access == null || access.getRoles() == null) {
            context.setAttribute(AuthorizationPolicy.AUTHENTICATED_USER_ROLES, Collections.<String>emptySet());
        } else {
            context.setAttribute(AuthorizationPolicy.AUTHENTICATED_USER_ROLES, access.getRoles());
        }
    }
}
 
Example 3
Source File: RoleResolveUtil.java    From keycloak with Apache License 2.0 6 votes vote down vote up
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 4
Source File: AbstractUserRoleMappingMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
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 5
Source File: RoleResolveUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * 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 6
Source File: OAuthGrantTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@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 7
Source File: KeycloakIdentity.java    From keycloak with Apache License 2.0 4 votes vote down vote up
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);
}