8000 Grant roles when an organization invitation is accepted by SferaDev · Pull Request #52788 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
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
@@ -1,5 +1,7 @@
package org.keycloak.representations.idm;

import java.util.List;

/**
* Representation of an organization invitation.
*/
Expand All @@ -18,6 +20,7 @@ public enum Status {
private int sentDate;
private int expiresAt;
private Status status;
private List<RoleRepresentation> roles;
@Deprecated
private String inviteLink;

Expand Down Expand Up @@ -88,6 +91,14 @@ public void setStatus(Status status) {
this.status = status;
}

public List<RoleRepresentation> getRoles() {
return roles;
}

public void setRoles(List<RoleRepresentation> roles) {
this.roles = roles;
}

/**
* @deprecated The invite link is no longer exposed in API responses.
*/
Expand Down
4 changes: 4 additions & 0 deletions docs/documentation/release_notes/topics/27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ This removes the need for a separate API call to discover the service account us
The dedicated `GET /admin/realms/\{realm}/clients/\{id}/service-account-user` endpoint has been removed.
See the upgrading guide for migration details.

== Roles granted with organization invitations

When inviting a user to an organization through the Admin REST API, you can now select realm roles and client roles for the invitation. The roles are granted together with the membership when the invitee joins, whether they accept the invitation through the invitation link, the registration flow, or an identity provider. For details, see the link:{adminguide_link}#_organization_invitation_roles[{adminguide_name}].

= Security and Standards

== Post-quantum WebAuthn signatures (experimental)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,19 @@ identity provider they choose skips that flow, so the invitation is not accepted

IMPORTANT: The invitation is accepted through any identity provider in the realm, not only those associated with the organization.

[[_organization_invitation_roles]]
=== Granting roles with an invitation

When sending an invitation through the Admin REST API, you can include the ids of realm roles or client roles using the
`roles` form parameter of the `invite-user` and `invite-existing-user` endpoints. The roles are granted to the user in the
same transaction that adds the user as a member of the organization, whether the invitation is accepted through the
invitation link, the registration flow, or an identity provider.

The administrator sending the invitation must be allowed to map each of the roles to the user, using the same permissions
required to grant the roles directly. When the invitation is for a user who does not have an account yet, the administrator
must be allowed to map roles to any user in the realm. Roles deleted before the invitation is accepted are removed from the
invitation, and resending an invitation keeps its roles.

== Managing invitations

{project_name} provides comprehensive invitation management capabilities that allow administrators to track, manage, and control
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,25 @@ Response inviteUser(@FormParam("email") String email,
@FormParam("lastName") String lastName,
@QueryParam("client_id") String clientId);

/**
* Invites a user by e-mail, granting the given roles when the invitation is accepted.
*
* @param email the e-mail address of the user to invite.
* @param firstName the first name of the user to invite.
* @param lastName the last name of the user to invite.
* @param clientId the id of the client the user is redirected to after accepting the invitation.
* @param roleIds the ids of the realm or client roles granted to the user when the invitation is accepted.
* @since Keycloak server 27
*/
@POST
@Path("invite-user")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
Response inviteUser(@FormParam("email") String email,
@FormParam("firstName") String firstName,
@FormParam("lastName") String lastName,
@QueryParam("client_id") String clientId,
@FormParam("roles") List<String> roleIds);

/**
* @deprecated Use {@link #inviteExistingUser(String, String)} with an explicit {@code client_id} instead.
*/
Expand All @@ -220,6 +239,21 @@ Response inviteUser(@FormParam("email") String email,
Response inviteExistingUser(@FormParam("id") String id,
@QueryParam("client_id") String clientId);

/**
* Invites an existing user, granting the given roles when the invitation is accepted.
*
* @param id the id of the user to invite.
* @param clientId the id of the client the user is redirected to after accepting the invitation.
* @param roleIds the ids of the realm or client roles granted to the user when the invitation is accepted.
* @since Keycloak server 27
*/
@POST
@Path("invite-existing-user")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
Response inviteExistingUser(@FormParam("id") String id,
@QueryParam("client_id") String clientId,
@FormParam("roles") List<String> roleIds);

/**
* @since Keycloak server 26
* @return count of members of the organization
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type RoleRepresentation from "./roleRepresentation.js";

export enum OrganizationInvitationStatus {
PENDING = "PENDING",
EXPIRED = "EXPIRED",
Expand All @@ -12,6 +14,7 @@ export default interface OrganizationInvitationRepresentation {
sentDate?: number;
expiresAt?: number;
status?: OrganizationInvitationStatus;
roles?: RoleRepresentation[];
/** @deprecated The invite link is no longer exposed in API responses. */
inviteLink?: string;
}
Original file line number Diff line number Diff line change
Expand Up @@ -923,6 +923,10 @@ public void preRemove(RealmModel realm, RoleModel role) {
// ClientProvider implementation
String clientScopeMapping = JpaUtils.getTableNameForNativeQuery("SCOPE_MAPPING", em);
em.createNativeQuery("delete from " + clientScopeMapping + " where ROLE_ID = :role").setParameter("role", role.getId()).executeUpdate();

// OrganizationProvider implementation
String orgInvitationRole = JpaUtils.getTableNameForNativeQuery("ORG_INVITATION_ROLE", em);
em.createNativeQuery("delete from " + orgInvitationRole + " where ROLE_ID = :role").setParameter("role", role.getId()).executeUpdate();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,24 @@
*/
package org.keycloak.models.jpa.entities;

import java.util.HashSet;
import java.util.Set;

import jakarta.persistence.CollectionTable;
import jakarta.persistence.Column;
import jakarta.persistence.ElementCollection;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.NamedQueries;
import jakarta.persistence.NamedQuery;
import jakarta.persistence.Table;

import org.keycloak.common.util.Time;
import org.keycloak.models.OrganizationInvitationModel;

import org.hibernate.annotations.BatchSize;

/**
* JPA entity for organization invitations.
*/
Expand Down Expand Up @@ -61,6 +69,12 @@ public class OrganizationInvitationEntity implements OrganizationInvitationModel
@Column(name = "INVITE_LINK", length = 2048)
private String inviteLink;

@ElementCollection
@BatchSize(size = 20)
@Column(name = "ROLE_ID")
@CollectionTable(name = "ORG_INVITATION_ROLE", joinColumns = { @JoinColumn(name = "INVITATION_ID") })
private Set<String> roleIds = new HashSet<>();
Comment thread
SferaDev marked this conversation as resolved.
Resolved

public OrganizationInvitationEntity() {
}

Expand Down Expand Up @@ -151,6 +165,17 @@ public void setInviteLink(String inviteLink) {
this.inviteLink = inviteLink;
}

@Override
public Set<String> getRoleIds() {
return roleIds;
}
Comment thread
SferaDev marked this conversation as resolved.
Resolved

@Override
public void setRoleIds(Set<String> roleIds) {
this.roleIds.clear();
this.roleIds.addAll(roleIds);
}

@Override
public InvitationStatus getStatus() {
return isExpired() ? InvitationStatus.EXPIRED : InvitationStatus.PENDING;
Expand Down
31 changes: 31 additions & 0 deletions model/jpa/src/main/resources/META-INF/jpa-changelog-27.0.0.xml
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,35 @@
</modifySql>
</changeSet>

<changeSet author="keycloak" id="27.0.0-org-invitation-role">
<preConditions >
<not>
<tableExists tableName="ORG_INVITATION_ROLE"/>
</not>
</preConditions>
<createTable tableName="ORG_INVITATION_ROLE">
<column name="INVITATION_ID" type="VARCHAR(36)">
<constraints nullable="false"/>
</column>
<column name="ROLE_ID" type="VARCHAR(255)">
<constraints nullable="false"/>
</column>
</createTable>

<addPrimaryKey tableName="ORG_INVITATION_ROLE"
columnNames="INVITATION_ID, ROLE_ID"
constraintName="PK_ORG_INVITATION_ROLE"/>

<createIndex indexName="IDX_ORG_INVITATION_ROLE_ROLE" tableName="ORG_INVITATION_ROLE">
<column name="ROLE_ID" type="VARCHAR(255)"/>
</createIndex>

<addForeignKeyConstraint baseTableName="ORG_INVITATION_ROLE"
baseColumnNames="INVITATION_ID"
constraintName="FK_ORG_INVITATION_ROLE_INV"
referencedTableName="ORG_INVITATION"
referencedColumnNames="ID"
>
</changeSet>

</databaseChangeLog>
10BC8
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
*/
package org.keycloak.models;

import java.util.Set;

import org.keycloak.common.util.Time;

/**
Expand Down Expand Up @@ -140,6 +142,30 @@ enum InvitationStatus {
*/
void setInviteLink(String inviteLink);

/**
* Returns the ids of the roles granted to the invitee when the invitation is accepted.
*
* <p>Both accessors have a default so that implementations written before roles existed keep working, as the
* APIs in this module do not change between minor releases. An implementation that stores no roles reads back
* none, while one asked to store roles fails instead of dropping them, since the caller checked the permissions
* to grant them.
*
* @return the role ids, empty if the invitation grants no roles
*/
default Set<String> getRoleIds() {
return Set.of();
}

/**
* Sets the ids of the roles granted to the invitee when the invitation is accepted.
*
* @param roleIds the role ids
* @throws UnsupportedOperationException if this invitation cannot store roles
*/
default void setRoleIds(Set<String> roleIds) {
throw new UnsupportedOperationException("Roles are not supported by this invitation model");
}

/**
* Returns the current status of this invitation.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,7 @@ public Response handleToken(InviteOrgActionToken token, ActionTokenContext<Invit

// if we made it this far then go ahead and add the user to the organization
orgProvider.addMember(orgProvider.getById(token.getOrgId()), user);
Organizations.grantInvitationRoles(session, realm, user, invitation, token.getUserId());

// Delete the invitation since it has been used
invitationManager.remove(token.getId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -369,8 +369,10 @@ private void addOrganizationMember(FormContext context, UserModel user) {
provider.addManagedMember(orgModel, user);
context.getAuthenticationSession().setRedirectUri(token.getRedirectUri());

// Delete the invitation since it has been used
InvitationManager invitationManager = provider.getInvitationManager();
Organizations.grantInvitationRoles(session, context.getRealm(), user, invitationManager.getById(token.getId()), token.getUserId());

// Delete the invitation since it has been used
invitationManager.remove(token.getId());

context.getEvent()
Expand Down
Loading
Loading
0