This repository has been archived by the owner on Oct 27, 2020. It is now read-only.
/
IdentityServiceRemoteUserMapper.java
248 lines (214 loc) · 8.03 KB
/
IdentityServiceRemoteUserMapper.java
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
/*
* #%L
* Alfresco Repository
* %%
* Copyright (C) 2005 - 2016 Alfresco Software Limited
* %%
* This file is part of the Alfresco software.
* If the software was purchased under a paid Alfresco license, the terms of
* the paid license agreement will prevail. Otherwise, the software is
* provided under the following open source license terms:
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
* #L%
*/
package org.alfresco.repo.security.authentication.identityservice;
import javax.servlet.http.HttpServletRequest;
import org.alfresco.repo.management.subsystems.ActivateableBean;
import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.security.authentication.AuthenticationUtil.RunAsWork;
import org.alfresco.repo.security.authentication.external.RemoteUserMapper;
import org.alfresco.service.cmr.security.PersonService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.keycloak.adapters.KeycloakDeployment;
import org.keycloak.adapters.spi.AuthOutcome;
import org.keycloak.representations.AccessToken;
/**
* A {@link RemoteUserMapper} implementation that detects and validates JWTs
* issued by the Alfresco Identity Service.
*
* @author Gavin Cornwell
*/
public class IdentityServiceRemoteUserMapper implements RemoteUserMapper, ActivateableBean
{
private static Log logger = LogFactory.getLog(IdentityServiceRemoteUserMapper.class);
/** Is the mapper enabled */
private boolean isEnabled;
/** Are token validation failures handled silently? */
private boolean isValidationFailureSilent;
/** The person service. */
private PersonService personService;
/** The Keycloak deployment object */
private KeycloakDeployment keycloakDeployment;
/**
* Sets the active flag
*
* @param isEnabled true to enable the subsystem
*/
public void setActive(boolean isEnabled)
{
this.isEnabled = isEnabled;
}
/**
* Determines whether token validation failures are silent
*
* @param silent true to silently fail, false to throw an exception
*/
public void setValidationFailureSilent(boolean silent)
{
this.isValidationFailureSilent = silent;
}
/**
* Sets the person service.
*
* @param personService
* the person service
*/
public void setPersonService(PersonService personService)
{
this.personService = personService;
}
public void setIdentityServiceDeployment(KeycloakDeployment deployment)
{
this.keycloakDeployment = deployment;
}
/*
* (non-Javadoc)
* @see org.alfresco.web.app.servlet.RemoteUserMapper#getRemoteUser(javax.servlet.http.HttpServletRequest)
*/
public String getRemoteUser(HttpServletRequest request)
{
try
{
if (logger.isTraceEnabled())
{
logger.trace("Retrieving username from http request...");
}
if (!this.isEnabled)
{
if (logger.isDebugEnabled())
{
logger.debug("IdentityServiceRemoteUserMapper is disabled, returning null.");
}
return null;
}
String headerUserId = extractUserFromHeader(request);
if (headerUserId != null)
{
// Normalize the user ID taking into account case sensitivity settings
String normalizedUserId = normalizeUserId(headerUserId);
if (logger.isTraceEnabled())
{
logger.trace("Returning userId: " + AuthenticationUtil.maskUsername(normalizedUserId));
}
return normalizedUserId;
}
}
catch (Exception e)
{
logger.error("Failed to authenticate user using IdentityServiceRemoteUserMapper: " + e.getMessage(), e);
}
if (logger.isTraceEnabled())
{
logger.trace("Could not identify a userId. Returning null.");
}
return null;
}
/*
* (non-Javadoc)
* @see org.alfresco.repo.management.subsystems.ActivateableBean#isActive()
*/
public boolean isActive()
{
return this.isEnabled;
}
/**
* Extracts the user name from the JWT in the given request.
*
* @param request The request containing the JWT
* @return The user name or null if it can not be determined
*/
private String extractUserFromHeader(HttpServletRequest request)
{
String userName = null;
IdentityServiceHttpFacade facade = new IdentityServiceHttpFacade(request);
// try authenticating with bearer token first
if (logger.isDebugEnabled())
{
logger.debug("Trying bearer token...");
}
AlfrescoBearerTokenRequestAuthenticator tokenAuthenticator =
new AlfrescoBearerTokenRequestAuthenticator(this.keycloakDeployment);
AuthOutcome tokenOutcome = tokenAuthenticator.authenticate(facade);
if (logger.isDebugEnabled())
{
logger.debug("Bearer token outcome: " + tokenOutcome);
}
if (tokenOutcome == AuthOutcome.FAILED && !isValidationFailureSilent)
{
throw new AuthenticationException("Token validation failed: " +
tokenAuthenticator.getValidationFailureDescription());
}
if (tokenOutcome == AuthOutcome.AUTHENTICATED)
{
userName = extractUserFromToken(tokenAuthenticator.getToken());
}
else
{
if (logger.isDebugEnabled())
{
logger.debug("User could not be authenticated by IdentityServiceRemoteUserMapper.");
}
}
return userName;
}
private String extractUserFromToken(AccessToken jwt)
{
// retrieve the preferred_username claim
String userName = jwt.getPreferredUsername();
if (logger.isTraceEnabled())
{
logger.trace("Extracted username: " + AuthenticationUtil.maskUsername(userName));
}
return userName;
}
/**
* Normalizes a user id, taking into account existing user accounts and case sensitivity settings.
*
* @param userId
* the user id
* @return the string
*/
private String normalizeUserId(final String userId)
{
if (userId == null)
{
return null;
}
String normalized = AuthenticationUtil.runAs(new RunAsWork<String>()
{
public String doWork() throws Exception
{
return personService.getUserIdentifier(userId);
}
}, AuthenticationUtil.getSystemUserName());
if (logger.isDebugEnabled())
{
logger.debug("Normalized user name for '" + AuthenticationUtil.maskUsername(userId) + "': " + AuthenticationUtil.maskUsername(normalized));
}
return normalized == null ? userId : normalized;
}
}