Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,6 @@ public final class Constants {
public static final String CLIENT_PROFILES = "client-policies.profiles";
public static final String CLIENT_POLICIES = "client-policies.policies";

public static final String INTROSPECTABLE_CLAIMS_CLAIM_NAME = "isc";
public static final String SKIP_ACCESS_TOKEN_SHORTENER_SESSION_ATTRIBUTE = "skipAccessTokenShortener";
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,72 +67,45 @@ public KeycloakIdentity(KeycloakSession keycloakSession, IDToken token) {
}

public KeycloakIdentity(IDToken token, KeycloakSession keycloakSession, RealmModel realm) {
if (token == 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);
}
if (realm == null) {
throw new ErrorResponseException("no_keycloak_session", "No realm set", Status.FORBIDDEN);
}
this.keycloakSession = keycloakSession;
this.realm = realm;

Map<String, Collection<String>> attributes = new HashMap<>();

try {
ObjectNode objectNode = JsonSerialization.createObjectNode(token);
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);
}
}
} catch (Exception e) {
throw new RuntimeException("Error while reading attributes from security token.", e);
}
requireToken(token);
this.keycloakSession = requireSession(keycloakSession);
this.realm = requireRealm(realm);

UserModel user = null;
AccessToken accessToken;
if (token instanceof AccessToken) {
this.accessToken = AccessToken.class.cast(token);
accessToken = (AccessToken) token;
} else {
UserSessionProvider sessions = keycloakSession.sessions();
UserSessionModel userSession = sessions.getUserSession(realm, token.getSessionState());

if (userSession == null) {
userSession = sessions.getOfflineUserSession(realm, token.getSessionState());
}

if (userSession == null) {
throw new RuntimeException("No active session associated with the token");
}

user = userSession.getUser();

ClientModel client = realm.getClientByClientId(token.getIssuedFor());
AuthenticatedClientSessionModel clientSessionModel = userSession.getAuthenticatedClientSessions().get(client.getId());
AuthenticatedClientSessionModel clientSessionModel =
userSession.getAuthenticatedClientSessions().get(client.getId());

ClientSessionContext clientSessionCtx =
DefaultClientSessionContext.fromClientSessionScopeParameter(clientSessionModel, keycloakSession);
accessToken = new TokenManager().createClientAccessToken(keycloakSession, realm, client, user, userSession,
clientSessionCtx);
}

accessToken = new TokenManager().completeIntrospectableAccessToken(accessToken, keycloakSession, realm);
Map<String, Collection<String>> attributes = createAttributesFromToken(accessToken);

this.accessToken = accessToken;

ClientSessionContext clientSessionCtx = DefaultClientSessionContext.fromClientSessionScopeParameter(clientSessionModel, keycloakSession);
this.accessToken = new TokenManager().createClientAccessToken(keycloakSession, realm, client, userSession.getUser(), userSession, clientSessionCtx);
if (user == null) {
user = getUserFromToken();
}

AccessToken.Access realmAccess = this.accessToken.getRealmAccess();
Expand All @@ -144,7 +117,8 @@ public KeycloakIdentity(IDToken token, KeycloakSession keycloakSession, RealmMod
Map<String, AccessToken.Access> resourceAccess = this.accessToken.getResourceAccess();

if (resourceAccess != null) {
resourceAccess.forEach((clientId, access) -> attributes.put("kc.client." + clientId + ".roles", access.getRoles()));
resourceAccess.forEach(
(clientId, access) -> attributes.put("kc.client." + clientId + ".roles", access.getRoles()));
}

ClientModel clientModel = getTargetClient();
Expand All @@ -154,34 +128,68 @@ public KeycloakIdentity(IDToken token, KeycloakSession keycloakSession, RealmMod
clientUser = this.keycloakSession.users().getServiceAccount(clientModel);
}

UserModel userSession = getUserFromToken();

this.resourceServer = clientUser != null && userSession.getId().equals(clientUser.getId());
this.resourceServer = clientUser != null && user.getId().equals(clientUser.getId());

if (resourceServer) {
this.id = clientModel.getId();
} else {
this.id = userSession.getId();
this.id = user.getId();
}

this.attributes = Attributes.from(attributes);
}

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);
this(requireToken(accessToken), requireSession(keycloakSession),
requireRealm(keycloakSession.getContext().getRealm()));
}

@Override
public String getId() {
return this.id;
}

@Override
public Attributes getAttributes() {
return this.attributes;
}


public AccessToken getAccessToken() {
return this.accessToken;
}

public boolean isResourceServer() {
return this.resourceServer;
}

private static RealmModel requireRealm(RealmModel realm) {
if (realm == null) {
throw new ErrorResponseException("no_keycloak_session", "No realm set", Status.FORBIDDEN);
}
return realm;
}

private static KeycloakSession requireSession(KeycloakSession keycloakSession) {
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();
return keycloakSession;
}

private static <T extends IDToken> T requireToken(T token) {
if (token == null) {
throw new ErrorResponseException("invalid_bearer_token",
"Could not obtain bearer access_token from request.", Status.FORBIDDEN);
}
return token;
}

private static Map<String, Collection<String>> createAttributesFromToken(IDToken token) {
Map<String, Collection<String>> attributes = new HashMap<>();

try {
ObjectNode objectNode = JsonSerialization.createObjectNode(this.accessToken);
ObjectNode objectNode = JsonSerialization.createObjectNode(token);
Iterator<String> iterator = objectNode.fieldNames();

while (iterator.hasNext()) {
Expand All @@ -190,10 +198,8 @@ public KeycloakIdentity(AccessToken accessToken, KeycloakSession keycloakSession
List<String> values = new ArrayList<>();

if (fieldValue.isArray()) {
Iterator<JsonNode> valueIterator = fieldValue.iterator();

while (valueIterator.hasNext()) {
values.add(valueIterator.next().asText());
for (JsonNode jsonNode : fieldValue) {
values.add(jsonNode.asText());
}
} else {
String value = fieldValue.asText();
Expand All @@ -209,58 +215,10 @@ public KeycloakIdentity(AccessToken accessToken, KeycloakSession keycloakSession
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 = getUserFromToken();

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);
}

@Override
public String getId() {
return this.id;
}

@Override
public Attributes getAttributes() {
return this.attributes;
}

public AccessToken getAccessToken() {
return this.accessToken;
}

public boolean isResourceServer() {
return this.resourceServer;
return attributes;
}

private ClientModel getTargetClient() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,12 @@ public class ProtocolMapperUtils {
// Add roles to tokens finally
public static final int PRIORITY_ROLE_MAPPER = 40;

// Script mapper goes last, so it can access the roles in the token
// Script mapper goes after roles, so it can access the roles in the token
public static final int PRIORITY_SCRIPT_MAPPER = 50;

// Shortener mapper goes last, so it can access all token content
public static final int PRIORITY_ACCESS_TOKEN_SHORTENER = 60;

public static String getUserModelValue(UserModel user, String propertyName) {

String methodName = "get" + Character.toUpperCase(propertyName.charAt(0)) + propertyName.substring(1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
*/
package org.keycloak.protocol.oidc;

import com.fasterxml.jackson.databind.node.ObjectNode;
import org.jboss.logging.Logger;
import org.keycloak.TokenVerifier;
import org.keycloak.common.VerificationException;
Expand All @@ -30,6 +29,8 @@
import org.keycloak.services.Urls;
import org.keycloak.util.JsonSerialization;

import com.fasterxml.jackson.databind.node.ObjectNode;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

Expand All @@ -55,14 +56,16 @@ public Response introspect(String token) {
ObjectNode tokenMetadata;

if (accessToken != null) {
tokenMetadata = JsonSerialization.createObjectNode(accessToken);
tokenMetadata.put("client_id", accessToken.getIssuedFor());
AccessToken introspectedAccessToken = completeIntrospectableClaims(accessToken);
tokenMetadata = JsonSerialization.createObjectNode(introspectedAccessToken);

if (!tokenMetadata.has("username")) {
if (accessToken.getPreferredUsername() != null) {
tokenMetadata.put("username", accessToken.getPreferredUsername());
tokenMetadata.put("client_id", introspectedAccessToken.getIssuedFor());

if (tokenMetadata.get("username") == null) {
if (introspectedAccessToken.getPreferredUsername() != null) {
tokenMetadata.put("username", introspectedAccessToken.getPreferredUsername());
} else {
UserModel userModel = session.users().getUserById(realm, accessToken.getSubject());
UserModel userModel = session.users().getUserById(realm, introspectedAccessToken.getSubject());
if (userModel != null) {
tokenMetadata.put("username", userModel.getUsername());
}
Expand All @@ -80,6 +83,10 @@ public Response introspect(String token) {
}
}

private AccessToken completeIntrospectableClaims(final AccessToken inputToken) {
return tokenManager.completeIntrospectableAccessToken(inputToken, session, realm);
}

protected AccessToken verifyAccessToken(String token) {
AccessToken accessToken;

Expand Down
Loading