Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
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 @@ -27,8 +27,10 @@
import org.keycloak.authorization.policy.evaluation.Evaluation;
import org.keycloak.authorization.policy.provider.PolicyProvider;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.RoleModel;
import org.keycloak.models.UserModel;
import org.keycloak.representations.idm.authorization.RolePolicyRepresentation;

/**
Expand All @@ -47,7 +49,8 @@ public RolePolicyProvider(BiFunction<Policy, AuthorizationProvider, RolePolicyRe
@Override
public void evaluate(Evaluation evaluation) {
Policy policy = evaluation.getPolicy();
Set<RolePolicyRepresentation.RoleDefinition> roleIds = representationFunction.apply(policy, evaluation.getAuthorizationProvider()).getRoles();
RolePolicyRepresentation policyRep = representationFunction.apply(policy, evaluation.getAuthorizationProvider());
Set<RolePolicyRepresentation.RoleDefinition> roleIds = policyRep.getRoles();
AuthorizationProvider authorizationProvider = evaluation.getAuthorizationProvider();
RealmModel realm = authorizationProvider.getKeycloakSession().getContext().getRealm();
Identity identity = evaluation.getContext().getIdentity();
Expand All @@ -56,7 +59,7 @@ public void evaluate(Evaluation evaluation) {
RoleModel role = realm.getRoleById(roleDefinition.getId());

if (role != null) {
boolean hasRole = hasRole(identity, role, realm);
boolean hasRole = hasRole(identity, role, realm, authorizationProvider, policyRep.isFetchRoles());

if (!hasRole && roleDefinition.isRequired()) {
evaluation.deny();
Expand All @@ -69,7 +72,12 @@ public void evaluate(Evaluation evaluation) {
logger.debugv("policy {} evaluated with status {} on identity {}", policy.getName(), evaluation.getEffect(), identity.getId());
}

private boolean hasRole(Identity identity, RoleModel role, RealmModel realm) {
private boolean hasRole(Identity identity, RoleModel role, RealmModel realm, AuthorizationProvider authorizationProvider, boolean fetchRoles) {
if (fetchRoles) {
KeycloakSession session = authorizationProvider.getKeycloakSession();
UserModel user = session.users().getUserById(realm, identity.getId());
return user.hasRole(role);
}
String roleName = role.getName();
if (role.isClientRole()) {
ClientModel clientModel = realm.getClientById(role.getContainerId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.keycloak.representations.idm.authorization.PolicyRepresentation;
import org.keycloak.representations.idm.authorization.RolePolicyRepresentation;
import org.keycloak.util.JsonSerialization;
import org.keycloak.utils.StringUtil;

import java.io.IOException;
import java.util.ArrayList;
Expand Down Expand Up @@ -87,6 +88,12 @@ public RolePolicyRepresentation toRepresentation(Policy policy, AuthorizationPro
representation.setRoles(new HashSet<>(
Arrays.asList(JsonSerialization.readValue(roles, RolePolicyRepresentation.RoleDefinition[].class))));
}

String fetchRoles = policy.getConfig().get("fetchRoles");

if (StringUtil.isNotBlank(fetchRoles)) {
representation.setFetchRoles(Boolean.parseBoolean(fetchRoles));
}
} catch (IOException cause) {
throw new RuntimeException("Failed to deserialize roles", cause);
}
Expand Down Expand Up @@ -116,6 +123,11 @@ public void onImport(Policy policy, PolicyRepresentation representation, Authori
} catch (IOException cause) {
throw new RuntimeException("Failed to deserialize roles during import", cause);
}
String fetchRoles = representation.getConfig().get("fetchRoles");

if (StringUtil.isNotBlank(fetchRoles)) {
policy.putConfig("fetchRoles", fetchRoles);
}
}

@Override
Expand All @@ -139,10 +151,17 @@ public void onExport(Policy policy, PolicyRepresentation representation, Authori
throw new RuntimeException("Failed to export role policy [" + policy.getName() + "]", cause);
}

String fetchRoles = policy.getConfig().get("fetchRoles");

if (StringUtil.isNotBlank(fetchRoles)) {
config.put("fetchRoles", fetchRoles);
}

representation.setConfig(config);
}

private void updateRoles(Policy policy, RolePolicyRepresentation representation, AuthorizationProvider authorization) {
policy.putConfig("fetchRoles", String.valueOf(representation.isFetchRoles()));
updateRoles(policy, authorization, representation.getRoles());
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
public class RolePolicyRepresentation extends AbstractPolicyRepresentation {

private Set<RoleDefinition> roles;
private boolean fetchRoles;

@Override
public String getType() {
Expand Down Expand Up @@ -58,6 +59,14 @@ public void addClientRole(String clientId, String name, boolean required) {
addRole(clientId + "/" + name, required);
}

public boolean isFetchRoles() {
return fetchRoles;
}

public void setFetchRoles(boolean fetchRoles) {
this.fetchRoles = fetchRoles;
}

public static class RoleDefinition {

private String id;
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ Specifies which *realm* roles are permitted by this policy.
+
Specifies which *client* roles are permitted by this policy. To enable this field must first select a `Client`.
+
* *Fetch Roles*
+
By default, only the roles available from the token sent with the authorization requests are used to check if the user is granted with a role. If this setting is enabled, the policy will ignore roles from the token and check any role associated with the user instead.
+
* *Logic*
+
The logic of this policy to apply after the other conditions have been evaluated.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3097,3 +3097,5 @@ addTranslationDialogHelperText=The translation based on the default language is
noLanguagesSearchResultsInstructions=Click on the search bar above to search for languages
addTranslationDialogOkBtn=Ok
translationError=Please add translations before saving
fetchRoles=Fetch Roles
fetchRolesHelp=By default, only the roles available from the token sent with the authorization requests are used to check if the user is granted with a role. If this setting is enabled, the policy will ignore roles from the token and check any role associated with the user instead.
211 changes: 110 additions & 101 deletions js/apps/admin-ui/src/clients/authorization/policy/Role.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { AddRoleMappingModal } from "../../../components/role-mapping/AddRoleMap
import { Row, ServiceRole } from "../../../components/role-mapping/RoleMapping";
import { useFetch } from "../../../utils/useFetch";
import type { RequiredIdValue } from "./ClientScope";
import { DefaultSwitchControl } from "../../../components/SwitchControl";

export const Role = () => {
const { t } = useTranslation();
Expand All @@ -28,6 +29,7 @@ export const Role = () => {
formState: { errors },
} = useFormContext<{
roles?: RequiredIdValue[];
fetchRoles?: boolean;
}>();
const values = getValues("roles");

Expand Down Expand Up @@ -58,109 +60,116 @@ export const Role = () => {
);

return (
<FormGroup
label={t("roles")}
labelIcon={
<HelpItem helpText={t("policyRolesHelp")} fieldLabelId="roles" />
}
fieldId="roles"
helperTextInvalid={t("requiredRoles")}
validated={errors.roles ? "error" : "default"}
isRequired
>
<Controller
name="roles"
control={control}
defaultValue={[]}
rules={{
validate: (value?: RequiredIdValue[]) =>
value && value.filter((c) => c.id).length > 0,
}}
render={({ field }) => (
<>
{open && (
<AddRoleMappingModal
id="role"
type="roles"
onAssign={(rows) => {
field.onChange([
...(field.value || []),
...rows.map((row) => ({ id: row.role.id })),
]);
setSelectedRoles([...selectedRoles, ...rows]);
setOpen(false);
}}
onClose={() => {
setOpen(false);
<>
<FormGroup
label={t("roles")}
labelIcon={
<HelpItem helpText={t("policyRolesHelp")} fieldLabelId="roles" />
}
fieldId="roles"
helperTextInvalid={t("requiredRoles")}
validated={errors.roles ? "error" : "default"}
isRequired
>
<Controller
name="roles"
control={control}
defaultValue={[]}
rules={{
validate: (value?: RequiredIdValue[]) =>
value && value.filter((c) => c.id).length > 0,
}}
render={({ field }) => (
<>
{open && (
<AddRoleMappingModal
id="role"
type="roles"
onAssign={(rows) => {
field.onChange([
...(field.value || []),
...rows.map((row) => ({ id: row.role.id })),
]);
setSelectedRoles([...selectedRoles, ...rows]);
setOpen(false);
}}
onClose={() => {
setOpen(false);
}}
isLDAPmapper
/>
)}
<Button
data-testid="select-role-button"
variant="secondary"
onClick={() => {
setOpen(true);
}}
isLDAPmapper
/>
)}
<Button
data-testid="select-role-button"
variant="secondary"
onClick={() => {
setOpen(true);
}}
>
{t("addRoles")}
</Button>
</>
>
{t("addRoles")}
</Button>
</>
)}
/>
{selectedRoles.length > 0 && (
<TableComposable variant="compact">
<Thead>
<Tr>
<Th>{t("roles")}</Th>
<Th>{t("required")}</Th>
<Th aria-hidden="true" />
</Tr>
</Thead>
<Tbody>
{selectedRoles.map((row, index) => (
<Tr key={row.role.id}>
<Td>
<ServiceRole role={row.role} client={row.client} />
</Td>
<Td>
<Controller
name={`roles.${index}.required`}
defaultValue={false}
control={control}
render={({ field }) => (
<Checkbox
id="required"
data-testid="standard"
name="required"
isChecked={field.value}
onChange={field.onChange}
/>
)}
/>
</Td>
<Td>
<Button
variant="link"
className="keycloak__client-authorization__policy-row-remove"
icon={<MinusCircleIcon />}
onClick={() => {
setValue("roles", [
...(values || []).filter((s) => s.id !== row.role.id),
]);
setSelectedRoles([
...selectedRoles.filter(
(s) => s.role.id !== row.role.id,
),
]);
}}
/>
</Td>
</Tr>
))}
</Tbody>
</TableComposable>
)}
</FormGroup>
<DefaultSwitchControl
name="fetchRoles"
label={t("fetchRoles")}
labelIcon={t("fetchRolesHelp")}
/>
{selectedRoles.length > 0 && (
<TableComposable variant="compact">
<Thead>
<Tr>
<Th>{t("roles")}</Th>
<Th>{t("required")}</Th>
<Th aria-hidden="true" />
</Tr>
</Thead>
<Tbody>
{selectedRoles.map((row, index) => (
<Tr key={row.role.id}>
<Td>
<ServiceRole role={row.role} client={row.client} />
</Td>
<Td>
<Controller
name={`roles.${index}.required`}
defaultValue={false}
control={control}
render={({ field }) => (
<Checkbox
id="required"
data-testid="standard"
name="required"
isChecked={field.value}
onChange={field.onChange}
/>
)}
/>
</Td>
<Td>
<Button
variant="link"
className="keycloak__client-authorization__policy-row-remove"
icon={<MinusCircleIcon />}
onClick={() => {
setValue("roles", [
...(values || []).filter((s) => s.id !== row.role.id),
]);
setSelectedRoles([
...selectedRoles.filter(
(s) => s.role.id !== row.role.id,
),
]);
}}
/>
</Td>
</Tr>
))}
</Tbody>
</TableComposable>
)}
</FormGroup>
</>
);
};
Loading