KeycloakServices.groovy
9.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import groovy.json.JsonOutput
import groovy.transform.Field
import java.sql.Timestamp
import java.util.Base64
import java.util.UUID
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import groovy.json.JsonSlurper
import org.moqui.util.RestClient
import org.moqui.util.ObjectUtilities
import org.moqui.context.ExecutionContext
import org.moqui.entity.EntityCondition
import org.moqui.entity.EntityFind
import org.moqui.entity.EntityList
import org.moqui.entity.EntityValue
import org.keycloak.OAuth2Constants
import org.keycloak.admin.client.Keycloak
import org.keycloak.admin.client.KeycloakBuilder
import org.keycloak.admin.client.resource.ClientResource
import org.keycloak.admin.client.resource.RealmResource
import org.keycloak.admin.client.resource.RoleMappingResource
import org.keycloak.admin.client.resource.RoleScopeResource
import org.keycloak.admin.client.resource.RolesResource
import org.keycloak.admin.client.resource.ServerInfoResource
import org.keycloak.admin.client.resource.UserResource
import org.keycloak.admin.client.resource.UsersResource
import org.keycloak.representations.idm.ClientMappingsRepresentation
import org.keycloak.representations.idm.MappingsRepresentation
import org.keycloak.representations.idm.RoleRepresentation
import org.keycloak.representations.idm.UserRepresentation
import org.keycloak.util.JsonSerialization
@Field Logger logger = LoggerFactory.getLogger('KeycloakServices')
Long timestampToKeycloak(Timestamp timestamp) {
return timestamp.getTime()
}
String keycloakToJson(Object o) {
return JsonSerialization.writeValueAsString(o)
}
Keycloak buildKeycloak() {
return KeycloakBuilder.builder()
.serverUrl('http://keycloak')
.realm('master')
.grantType(OAuth2Constants.CLIENT_CREDENTIALS)
.clientId('moqui')
.clientSecret('iXsnjGEbIVT8DQky2yCU9NQhnqDYyi7g')
.build()
}
Map<String, Object> buildClientConsent() {
return [
clientId: null,
createdDate: null, // int64
grantedClientScopes: [], // array[string]
lastUpdatedData: null, // int64
]
}
Map<String, Object> buildCredential() {
return [
createdDate: null, // int64
credentialData: null, // string
id: null, // string
priority: null, // int32
secretData: null, // string
temporary: null, // boolean
type: null, // string
userLabel: null, // string
value: null, // string
]
}
Map<String, Object> buildFederatedIdentiy() {
return [
identityProvider: null, // string
userId: null, // string
userName: null, // string
]
}
Map<String, Object> buildKeycloakUser(String userId) {
EntityValue userLogin = ec.entity.find('UserLogin').condition('userId', userId)
Map<String, Object> keycloakUser = [
access: [:],
attributes: [:],
clientConsents: [],
clientRoles: [:],
createdTimestamp: null, // int64
credentials: [],
disableableCredentialTypes: [], // array[string]
email: null, // string
emailVerified: null, // boolean
enabled: null, // boolean
federatedIdentities: [],
federationLink: null, // string
firstName: null,
groups: [], // array[string]
id: null, // string
lastName: null,
notBefore: null, // int32
origin: null, // string
realmRoles: [], // array[string]
requiredActions: [], // array[string]
self: null, // string
serviceClientId: null, // string
username: null, // string
]
return keycloakUser
}
Map<String, Object> onUpdateEmailAddress() {
}
Map<String, Object> joinUserAccountToKeycloak() {
String userId = context.userId
String externalUserId = context.externalUserId
if (externalUserId && externalUserId.startsWith('keycloak:')) {
// Already joined
return [:]
}
Keycloak keycloak = buildKeycloak()
try {
RealmResource realm = keycloak.realm('master')
UsersResource users = realm.users()
for (UserRepresentation user: users.list()) {
logger.info('keycloak user: ' + keycloakToJson(user))
}
} finally {
keycloak.close()
}
}
Map<String, Object> onUpdateUserAccount() {
String userId = context.userId
String externalUserId = context.externalUserId
if (!(externalUserId && externalUserId.startsWith('keycloak:'))) {
return [:]
}
String keycloakUserId = externalUserId.substring('keycloak:'.length())
}
Map<String, RoleRepresentation> getClientRoles(RealmResource realm, ClientResource clientResource, Collection<String> roleList) {
//logger.info('keycloak client: ' + keycloakToJson(clientResource))
logger.info("roleList(${roleList.size()})=${roleList}")
Map<String, RoleRepresentation> result = [:]
for (String role: roleList) {
result[role] = null
}
RolesResource rolesResource = clientResource.roles()
for (RoleRepresentation roleRep: rolesResource.list()) {
String name = roleRep.getName()
if (result.containsKey(name)) {
result[name] = roleRep
}
}
for (Map.Entry<String, RoleRepresentation> resultEntry: result.entrySet()) {
logger.info("got role mapping: (${resultEntry.getKey()})=(${resultEntry.getValue()})")
}
for (Map.Entry<String, RoleRepresentation> resultEntry: result.entrySet()) {
String name = resultEntry.getKey()
if (resultEntry.getValue() == null) {
rolesResource.create(new RoleRepresentation(name, "", false))
resultEntry.setValue(rolesResource.get(name))
}
}
return result
}
void updateUser(RealmResource realm, String keycloakClientId, String keycloakUserId, String userId) {
String clientId = realm.clients().findByClientId(keycloakClientId).get(0).getId()
logger.info("keycloakClientId=${keycloakClientId} clientId=${clientId}")
ClientResource clientResource = realm.clients().get(clientId)
UsersResource usersResource = realm.users()
UserResource userResource = usersResource.get(keycloakUserId)
Timestamp now = ec.user.nowTimestamp
List<EntityValue> userPermissionList = ec.entity.find('UserPermissionCheck')
.condition('userId', userId)
.useCache(true)
.disableAuthz()
.list()
.filterByDate('groupFromDate', 'groupThruDate', now)
.filterByDate('permissionFromDate', 'permissionThruDate', now)
List<String> moquiPermissions = userPermisionList*.userPermissionId.collect { permission -> 'permission:' + permission }
List<String> moquiGroups = ec.user.userGroupIdSet.collect { group -> 'group:' + group }
Map<String, RoleRepresentation> wantedClientRoles = getClientRoles(realm, clientResource, moquiPermissions + moquiGroups)
UserRepresentation userRep = userResource.toRepresentation()
Map<String, List<String>> attributes = new HashMap(userRep.getAttributes() ?: [:])
attributes['moqui:now'] = [now.toString()]
logger.info("user[$userId]} attributes: " + attributes)
userRep.setAttributes(attributes)
RoleMappingResource roleMappingResource = userResource.roles()
ClientMappingsRepresentation clientMappingsRespresentation = roleMappingResource.getAll().getClientMappings()[keycloakClientId]
for (RoleRepresentation existingRoleRep: clientMappingsRespresentation.getMappings()) {
if (!wantedClientRoles.remove(existingRoleRep.getName())) {
toRemove.add(existingRoleRep)
}
}
RoleScopeResource clientRoleScopeResource = roleMappingResource.clientLevel(clientId)
clientRoleScopeResource.remove(toRemove)
clientRoleScopeResource.add(wantedClientRoles.values() as List)
userResource.update(userRep)
}
Map<String, Object> pushKeycloakUser() {
String userId = context.userId
EntityValue userLogin = ec.entity.find('UserLogin').condition('userId', userId).one()
List<EntityValue> logins
return [:]
/*
<view-entity entity-name="UserPermissionCheck" package="moqui.security">
<member-entity entity-alias="UGM" entity-name="moqui.security.UserGroupMember"/>
<member-relationship entity-alias="UGP" join-from-alias="UGM" relationship="permissions"/>
<alias name="userGroupId" entity-alias="UGM"/>
<alias name="userId" entity-alias="UGM"/>
<alias name="userPermissionId" entity-alias="UGP"/>
<alias name="groupFromDate" entity-alias="UGM" field="fromDate"/>
<alias name="groupThruDate" entity-alias="UGM" field="thruDate"/>
<alias name="permissionFromDate" entity-alias="UGP" field="fromDate"/>
<alias name="permissionThruDate" entity-alias="UGP" field="thruDate"/>
</view-entity>
*/
}
Map<String, Object> getKeycloakUsers() {
String keycloakClientId = 'moqui'
Keycloak keycloak = buildKeycloak()
try {
RealmResource realm = keycloak.realm('master')
/*
ServerInfoResource serverInfo = keycloak.serverInfo()
logger.info('keycloak serverInfo: ' + keycloakToJson(serverInfo.getInfo()))
logger.info('keycloak keys: ' + keycloakToJson(realm.keys().getKeyMetadata()))
UsersResource users = realm.users()
for (UserRepresentation user: users.list()) {
logger.info('keycloak user: ' + keycloakToJson(user))
}
*/
updateUser(realm, keycloakClientId, 'c6a4cb53-4533-4236-89e5-058967b9b90a', '100000')
} finally {
keycloak.close()
}
}