TokenAuthenticationHandler.java
29.5 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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.adobe.granite.crypto.CryptoException
* com.adobe.granite.oauth.jwt.JwsBuilder
* com.adobe.granite.oauth.jwt.JwsBuilderFactory
* com.adobe.granite.oauth.jwt.JwsValidator
* javax.jcr.ItemNotFoundException
* javax.jcr.Node
* javax.jcr.RepositoryException
* javax.jcr.Session
* javax.jcr.SimpleCredentials
* javax.jcr.Workspace
* javax.servlet.http.HttpServletRequest
* javax.servlet.http.HttpServletResponse
* org.apache.felix.scr.annotations.Activate
* org.apache.felix.scr.annotations.Component
* org.apache.felix.scr.annotations.Deactivate
* org.apache.felix.scr.annotations.Properties
* org.apache.felix.scr.annotations.Property
* org.apache.felix.scr.annotations.PropertyOption
* org.apache.felix.scr.annotations.Reference
* org.apache.felix.scr.annotations.ReferenceCardinality
* org.apache.felix.scr.annotations.ReferencePolicy
* org.apache.felix.scr.annotations.Service
* org.apache.jackrabbit.api.security.authentication.token.TokenCredentials
* org.apache.sling.api.resource.ResourceResolver
* org.apache.sling.auth.core.AuthUtil
* org.apache.sling.auth.core.spi.AbstractAuthenticationHandler
* org.apache.sling.auth.core.spi.AuthenticationFeedbackHandler
* org.apache.sling.auth.core.spi.AuthenticationHandler
* org.apache.sling.auth.core.spi.AuthenticationInfo
* org.apache.sling.auth.core.spi.DefaultAuthenticationFeedbackHandler
* org.apache.sling.commons.osgi.OsgiUtil
* org.apache.sling.discovery.ClusterView
* org.apache.sling.discovery.InstanceDescription
* org.apache.sling.discovery.TopologyEvent
* org.apache.sling.discovery.TopologyEvent$Type
* org.apache.sling.discovery.TopologyEventListener
* org.apache.sling.discovery.TopologyView
* org.apache.sling.jcr.api.SlingRepository
* org.apache.sling.settings.SlingSettingsService
* org.osgi.framework.BundleContext
* org.osgi.framework.InvalidSyntaxException
* org.osgi.framework.ServiceReference
* org.osgi.framework.ServiceRegistration
* org.osgi.service.cm.Configuration
* org.osgi.service.cm.ConfigurationAdmin
* org.osgi.service.cm.ConfigurationEvent
* org.osgi.service.cm.ConfigurationListener
* org.osgi.service.component.ComponentContext
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.day.crx.security.token.impl;
import com.adobe.granite.crypto.CryptoException;
import com.adobe.granite.oauth.jwt.JwsBuilder;
import com.adobe.granite.oauth.jwt.JwsBuilderFactory;
import com.adobe.granite.oauth.jwt.JwsValidator;
import com.day.crx.security.token.TokenCookie;
import com.day.crx.security.token.impl.EncapsulatedTokenJaasHelper;
import com.day.crx.security.token.impl.FlexClientResponseHelper;
import java.io.IOException;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.Workspace;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.PropertyOption;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.api.security.authentication.token.TokenCredentials;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.auth.core.AuthUtil;
import org.apache.sling.auth.core.spi.AbstractAuthenticationHandler;
import org.apache.sling.auth.core.spi.AuthenticationFeedbackHandler;
import org.apache.sling.auth.core.spi.AuthenticationHandler;
import org.apache.sling.auth.core.spi.AuthenticationInfo;
import org.apache.sling.auth.core.spi.DefaultAuthenticationFeedbackHandler;
import org.apache.sling.commons.osgi.OsgiUtil;
import org.apache.sling.discovery.ClusterView;
import org.apache.sling.discovery.InstanceDescription;
import org.apache.sling.discovery.TopologyEvent;
import org.apache.sling.discovery.TopologyEventListener;
import org.apache.sling.discovery.TopologyView;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.settings.SlingSettingsService;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.cm.ConfigurationEvent;
import org.osgi.service.cm.ConfigurationListener;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
* This class specifies class file version 49.0 but uses Java 6 signatures. Assumed Java 6.
*/
@Component(metatype=1, label="%auth.token.name", description="%auth.token.description", name="com.day.crx.security.token.impl.impl.TokenAuthenticationHandler")
@Service(value={AuthenticationHandler.class, TopologyEventListener.class})
@Properties(value={@Property(name="path", value={"/"}), @Property(name="jaas.controlFlag", value={"sufficient"}), @Property(name="jaas.realmName", value={"jackrabbit.oak"}), @Property(name="jaas.ranking", intValue={2000})})
@Reference(name="jwsBuilderFactory", referenceInterface=JwsBuilderFactory.class, bind="bindJwsBuilderFactory", unbind="unbindJwsBuilderFactory")
public class TokenAuthenticationHandler
extends AbstractAuthenticationHandler
implements AuthenticationFeedbackHandler,
TopologyEventListener {
private static final String REQUEST_METHOD = "POST";
private static final String REQUEST_URL_SUFFIX = "/j_security_check";
private static final String PAR_J_USERNAME = "j_username";
private static final String PAR_J_PASSWORD = "j_password";
private static final String PAR_J_REASON = "j_reason";
private static final String PAR_J_SET_COOKIE = "j_set_cookie";
private static final String REASON_WRONG_CREDENTIALS = "invalid_login";
private static final String REASON_TOKEN_EXPIRED = "session_timed_out";
private static final String CREDENTIALS = "user.jcr.credentials";
private static final String AUTH_TYPE = "TOKEN";
private static final String ATTR_TOKEN = ".token";
private static final String ATTR_TOKEN_IP = "ip";
private static final String ATTR_TOKEN_IP_MANDATORY = ".token.ip";
private static final String ATTR_TOKEN_AGENT = "useragent";
private static final String ATTR_TOKEN_AGENT_MANDATORY = ".token.useragent";
private static final String ATTR_REFERER = "referer";
private static final String REQUIRED_ATTR_IP_AGENT = "ip_agent";
private static final String REQUIRED_ATTR_IP = "ip";
private static final String REQUIRED_ATTR_AGENT = "agent";
private static final String REQUIRED_ATTR_NONE = "none";
@Property(value={"ip"}, options={@PropertyOption(name="ip_agent", value="%token.required.attr.ip_agent"), @PropertyOption(name="ip", value="%token.required.attr.ip"), @PropertyOption(name="agent", value="%token.required.attr.agent"), @PropertyOption(name="none", value="%token.required.attr.none")})
private static final String PROP_REQUIRED_ATTR = "token.required.attr";
@Property
private static final String PROP_ALTERNATE_URL = "token.alternate.url";
@Property(boolValue={0})
private static final String PROP_ENABLE_ENCAPSULATED_TOKEN = "token.encapsulated";
private static final String NO_TOKEN = "";
private static final char[] NO_PASSWORD = new char[0];
protected static final String PID_TOKEN_CONFIGURATION = "org.apache.jackrabbit.oak.security.authentication.token.TokenConfigurationImpl";
protected static final String TOKEN_CONFIGURATION_EXPIRATION = "tokenExpiration";
private static final long TOKEN_EXPIRATION = 43200000;
protected static final String ENCAPSULATED_TOKEN_SCOPE = "scope";
protected static final String ENCAPSULATED_TOKEN_SCOPE_VALUE = "login";
private final Logger log;
@Property(name="service.description")
private static final String DESCRIPTION = "Token Authentication Handler";
private static final String RANDOM_UUID = UUID.randomUUID().toString();
@Reference
private SlingRepository repository;
@Reference
private SlingSettingsService settings;
private static volatile JwsBuilderFactory jwsBuilderFactory;
@Reference
private JwsValidator jwsValidator;
@Reference(policy=ReferencePolicy.DYNAMIC, cardinality=ReferenceCardinality.OPTIONAL_UNARY)
private volatile ConfigurationAdmin configAdmin;
private EncapsulatedTokenJaasHelper jaasHelper;
private String attrIp;
private String attrAgent;
private String alternateAuthUrl;
private volatile String clusterId;
private static volatile String repositoryId;
private BundleContext context;
private ServiceRegistration listenerReg;
private static volatile boolean encapsulatedToken;
private static volatile long tokenExpiration;
public TokenAuthenticationHandler() {
this.log = LoggerFactory.getLogger(this.getClass());
}
@Activate
private void activate(ComponentContext ctx) throws IOException, InvalidSyntaxException {
Dictionary configuration = ctx.getProperties();
this.context = ctx.getBundleContext();
String reqAttr = OsgiUtil.toString(configuration.get("token.required.attr"), (String)"ip_agent");
if ("ip".equals(reqAttr)) {
this.log.info("activate: Validating Cookie with Client IP");
this.attrIp = ".token.ip";
this.attrAgent = "useragent";
} else if ("agent".equals(reqAttr)) {
this.log.info("activate: Validating Cookie with Client User-Agent");
this.attrIp = "ip";
this.attrAgent = ".token.useragent";
} else if ("none".equals(reqAttr)) {
this.log.info("activate: Validating Token Only");
this.attrIp = "ip";
this.attrAgent = "useragent";
} else {
this.log.info("activate: Validating Cookie with Client IP and User-Agent");
this.attrIp = ".token.ip";
this.attrAgent = ".token.useragent";
}
this.alternateAuthUrl = OsgiUtil.toString(configuration.get("token.alternate.url"), (String)null);
if (this.alternateAuthUrl != null && !this.alternateAuthUrl.startsWith("/")) {
this.alternateAuthUrl = "/" + this.alternateAuthUrl;
}
if (TokenAuthenticationHandler.encapsulatedToken = OsgiUtil.toBoolean(configuration.get("token.encapsulated"), (boolean)false)) {
this.jaasHelper = new EncapsulatedTokenJaasHelper(this.jwsValidator);
this.jaasHelper.open(this.context, configuration);
this.listenerReg = this.context.registerService(ConfigurationListener.class.getName(), (Object)new TokenExpirationConfigListener(), null);
this.readTokenExpirationConfig(this.configAdmin);
}
this.initializeRepositoryId();
}
@Deactivate
private void deactivate() {
if (this.listenerReg != null) {
this.listenerReg.unregister();
}
if (this.jaasHelper != null) {
this.jaasHelper.close();
}
encapsulatedToken = false;
tokenExpiration = 43200000;
}
protected void bindJwsBuilderFactory(JwsBuilderFactory jwsBuilderFactory, Map<String, Object> properties) {
TokenAuthenticationHandler.jwsBuilderFactory = jwsBuilderFactory;
}
protected void unbindJwsBuilderFactory(JwsBuilderFactory jwsBuilderFactory, Map<String, Object> properties) {
TokenAuthenticationHandler.jwsBuilderFactory = null;
}
public void handleTopologyEvent(TopologyEvent event) {
if (event.getType() == TopologyEvent.Type.TOPOLOGY_CHANGED || event.getType() == TopologyEvent.Type.TOPOLOGY_INIT) {
this.clusterId = event.getNewView().getLocalInstance().getClusterView().getId();
this.initializeRepositoryId();
}
}
public AuthenticationInfo extractCredentials(HttpServletRequest request, HttpServletResponse response) {
AuthenticationInfo userNameInfo = this.getTokenFormPars(request);
if (userNameInfo != null) {
request.setAttribute("/j_security_check", (Object)"TOKEN");
return userNameInfo;
}
TokenCookie.Info info = TokenCookie.getTokenInfo(request, TokenAuthenticationHandler.getRepositoryId(encapsulatedToken));
if (info.token != null) {
if (this.log.isDebugEnabled()) {
this.log.debug("Extracted token information: {}@{}", (Object)info.token, (Object)info.workspace);
}
if (info.workspace != null && info.workspace.length() > 0) {
request.setAttribute("j_workspace", (Object)info.workspace);
}
TokenCredentials creds = TokenAuthenticationHandler.createCredentials(info.token);
return this.createAuthenticationInfo(creds, request);
}
return null;
}
public boolean requestCredentials(HttpServletRequest request, HttpServletResponse response) {
return false;
}
public void dropCredentials(HttpServletRequest request, HttpServletResponse response) {
if (!encapsulatedToken) {
this.removeTokenNode(request);
}
TokenCookie.update(request, response, TokenAuthenticationHandler.getRepositoryId(encapsulatedToken), null, null, true);
if (this.isFlexRequest(request) && request.getAttribute("j_reason") == null) {
HashMap<String, String> responseContent = new HashMap<String, String>();
responseContent.put("authenticated", "false");
responseContent.put("authstate", FlexClientResponseHelper.AuthState.LOGGED_OUT.name());
FlexClientResponseHelper.writeResponse(response, responseContent);
}
}
public void authenticationFailed(HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo) {
FlexClientResponseHelper.AuthFailedReason flexFailureReason;
if (TokenCookie.getTokenInfo((HttpServletRequest)request, (String)TokenAuthenticationHandler.getRepositoryId((boolean)TokenAuthenticationHandler.encapsulatedToken)).token != null) {
request.setAttribute("j_reason", (Object)"session_timed_out");
flexFailureReason = FlexClientResponseHelper.AuthFailedReason.TOKEN_EXPIRED;
} else {
request.setAttribute("j_reason", (Object)"invalid_login");
flexFailureReason = FlexClientResponseHelper.AuthFailedReason.WRONG_CREDENTIALS;
}
this.dropCredentials(request, response);
if (this.isFlexRequest(request)) {
HashMap<String, String> responseContent = new HashMap<String, String>();
responseContent.put("reason", flexFailureReason.name());
responseContent.put("authenticated", "false");
responseContent.put("authstate", FlexClientResponseHelper.AuthState.FAILED.name());
FlexClientResponseHelper.writeResponse(response, responseContent);
}
}
public boolean authenticationSucceeded(HttpServletRequest request, HttpServletResponse response, AuthenticationInfo authInfo) {
String resource;
boolean doRedirect = "POST".equals(request.getMethod()) && this.isLoginURL(request);
TokenCookie.Info tokenInfo = TokenCookie.getTokenInfo(request, TokenAuthenticationHandler.getRepositoryId(encapsulatedToken));
if ((doRedirect || this.needsCookieUpdate(tokenInfo, request)) && (tokenInfo = this.createTokenInfo(request, authInfo)) != null) {
TokenCookie.update(request, response, TokenAuthenticationHandler.getRepositoryId(encapsulatedToken), tokenInfo.token, tokenInfo.workspace, true);
}
boolean result = false;
if (this.isFlexRequest(request) && !this.logoutRequest(request)) {
HashMap<String, String> responseContent = new HashMap<String, String>();
responseContent.put("authenticated", "true");
responseContent.put("authstate", FlexClientResponseHelper.AuthState.COMPLETE.name());
responseContent.put("authtype", "TOKEN");
Object rrObj = request.getAttribute("org.apache.sling.auth.core.ResourceResolver");
if (rrObj instanceof ResourceResolver) {
String userId = ((ResourceResolver)rrObj).getUserID();
responseContent.put("userid", userId);
}
FlexClientResponseHelper.writeResponse(response, responseContent);
result = true;
} else if (doRedirect && !DefaultAuthenticationFeedbackHandler.handleRedirect((HttpServletRequest)request, (HttpServletResponse)response) && (resource = AuthUtil.getLoginResource((HttpServletRequest)request, (String)null)) != null) {
try {
response.sendRedirect(resource);
}
catch (IOException ioe) {
this.log.error("Failed to send redirect to: " + resource, (Throwable)ioe);
}
result = true;
}
return result;
}
private boolean isLoginURL(HttpServletRequest request) {
boolean result = request.getRequestURI().endsWith("/j_security_check");
if (!result && this.alternateAuthUrl != null) {
result = request.getRequestURI().endsWith(this.alternateAuthUrl);
}
return result;
}
private boolean logoutRequest(HttpServletRequest request) {
return "true".equalsIgnoreCase(request.getParameter("logout"));
}
private boolean isFlexRequest(HttpServletRequest request) {
return "true".equalsIgnoreCase(request.getParameter("j_flex"));
}
private void initializeRepositoryId() {
String id = this.clusterId;
if (id == null) {
id = this.settings.getSlingId();
if (id == null) {
id = RANDOM_UUID;
this.log.error("Failure to acquire unique ID for this token authenticator. Using random UUID {}", (Object)id);
} else {
this.log.info("ClusterId not known so far. Using the SlingId [{}] for unique identifier", (Object)id);
}
} else {
this.log.info("ClusterId determined using Topology Support [{}]", (Object)id);
}
repositoryId = id;
}
public static String getRepositoryId(boolean encapsulatedToken) {
if (encapsulatedToken) {
return "login";
}
String id = repositoryId;
if (id == null) {
id = RANDOM_UUID;
}
return id;
}
private AuthenticationInfo getTokenFormPars(HttpServletRequest request) {
if ("POST".equals(request.getMethod()) && this.isLoginURL(request) && request.getParameter("j_username") != null) {
if (!TokenAuthenticationHandler.isValidateRequest((HttpServletRequest)request)) {
String loginResource = AuthUtil.getLoginResource((HttpServletRequest)request, (String)request.getContextPath());
if (loginResource == null || loginResource.length() == 0) {
loginResource = "/";
}
TokenAuthenticationHandler.setLoginResourceAttribute((HttpServletRequest)request, (String)loginResource);
}
SimpleCredentials creds = TokenAuthenticationHandler.createCredentials(request.getParameter("j_username"), request.getParameter("j_password"));
return this.createAuthenticationInfo(creds, request);
}
return null;
}
public String toString() {
return "Token Authentication Handler";
}
private static TokenCredentials createCredentials(String token) {
return new TokenCredentials(token);
}
private static SimpleCredentials createCredentials(String userId, String password) {
SimpleCredentials creds = new SimpleCredentials(userId, password != null ? password.toCharArray() : NO_PASSWORD);
creds.setAttribute(".token", (Object)"");
return creds;
}
private AuthenticationInfo createAuthenticationInfo(SimpleCredentials creds, HttpServletRequest request) {
String referrer;
String ip;
String xff = request.getHeader("X-Forwarded-For");
if (xff == null) {
ip = request.getRemoteAddr();
} else {
String[] ips = xff.split(",");
ip = ips[ips.length - 1].trim();
}
creds.setAttribute(this.attrIp, (Object)ip);
String userAgent = request.getHeader("User-Agent");
if (userAgent != null) {
creds.setAttribute(this.attrAgent, (Object)userAgent);
}
if ((referrer = request.getHeader("Referer")) != null) {
creds.setAttribute("referer", (Object)referrer);
}
AuthenticationInfo info = new AuthenticationInfo("TOKEN");
info.put("user.jcr.credentials", (Object)creds);
return info;
}
private AuthenticationInfo createAuthenticationInfo(TokenCredentials creds, HttpServletRequest request) {
String ip;
String referrer;
String xff = request.getHeader("X-Forwarded-For");
if (xff == null) {
ip = request.getRemoteAddr();
} else {
String[] ips = xff.split(",");
ip = ips[ips.length - 1].trim();
}
String attrIp = !"".equals(creds.getAttribute(".token")) ? ".token.ip" : this.attrIp;
creds.setAttribute(attrIp, ip);
String userAgent = request.getHeader("User-Agent");
if (userAgent != null) {
String attrAgent = !"".equals(creds.getAttribute(".token")) ? ".token.useragent" : this.attrAgent;
creds.setAttribute(attrAgent, userAgent);
}
if ((referrer = request.getHeader("Referer")) != null) {
creds.setAttribute("referer", referrer);
}
AuthenticationInfo info = new AuthenticationInfo("TOKEN");
info.put("user.jcr.credentials", (Object)creds);
return info;
}
private boolean needsCookieUpdate(TokenCookie.Info info, HttpServletRequest request) {
return info.token == null || "true".equalsIgnoreCase(request.getParameter("j_set_cookie"));
}
/*
* Unable to fully structure code
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
* Lifted jumps to return sites
*/
private TokenCookie.Info createTokenInfo(HttpServletRequest request, AuthenticationInfo info) {
token = null;
creds = info.get((Object)"user.jcr.credentials");
workspace = null;
rrObj = request.getAttribute("org.apache.sling.auth.core.ResourceResolver");
if (rrObj instanceof ResourceResolver && (session = (Session)((ResourceResolver)rrObj).adaptTo(Session.class)) != null) {
workspace = session.getWorkspace().getName();
}
if (creds instanceof SimpleCredentials) {
if (TokenAuthenticationHandler.encapsulatedToken) {
try {
token = TokenAuthenticationHandler.buildEncapsulatedToken(((SimpleCredentials)creds).getUserID());
a = ((SimpleCredentials)creds).getAttribute(".token");
if (a == null) ** GOTO lbl25
node = a.toString();
this.removeTokenNode(node, workspace);
}
catch (CryptoException e) {
this.log.error("error while building the encapsulated token", (Throwable)e);
return null;
}
} else {
a = ((SimpleCredentials)creds).getAttribute(".token");
if (a != null) {
token = a.toString();
}
}
} else if (creds instanceof TokenCredentials) {
token = ((TokenCredentials)creds).getToken();
}
lbl25: // 6 sources:
if (token == null) return null;
if (workspace == null) return null;
return new TokenCookie.Info(token, workspace);
}
private void removeTokenNode(HttpServletRequest request) {
TokenCookie.Info tokenInfo = TokenCookie.getTokenInfo(request, TokenAuthenticationHandler.getRepositoryId(encapsulatedToken));
if (tokenInfo != null && tokenInfo.token != null) {
this.removeTokenNode(tokenInfo.token, tokenInfo.workspace);
}
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
private void removeTokenNode(String token, String workspace) {
Session session = null;
try {
int pos = token.indexOf(95);
String id = pos == -1 ? token : token.substring(0, pos);
session = this.repository.loginAdministrative(workspace);
session.getNodeByIdentifier(id).remove();
session.save();
}
catch (ItemNotFoundException infe) {
this.log.debug("removeTokenNode: Token node " + workspace + ":" + token + " not found", (Throwable)infe);
}
catch (RepositoryException re) {
this.log.info("removeTokenNode: Failed removing token node", (Throwable)re);
}
finally {
if (session != null) {
session.logout();
}
}
}
private void readTokenExpirationConfig(ConfigurationAdmin ca) throws IOException, InvalidSyntaxException {
if (ca == null) {
this.log.info("the ConfigurationAdmin is not available");
tokenExpiration = 43200000;
this.log.debug("token expiration is set at the default value {}", (Object)tokenExpiration);
return;
}
String filter = "(service.pid=org.apache.jackrabbit.oak.security.authentication.token.TokenConfigurationImpl)";
Configuration[] configs = ca.listConfigurations(filter);
if (configs != null && configs.length > 0) {
Configuration c = configs[0];
if (c == null) {
tokenExpiration = 43200000;
this.log.debug("token expiration is set at the default value {}", (Object)tokenExpiration);
}
Dictionary props = c.getProperties();
tokenExpiration = OsgiUtil.toLong(props.get("tokenExpiration"), (long)43200000);
this.log.debug("token expiration is set at {}", (Object)tokenExpiration);
} else {
tokenExpiration = 43200000;
this.log.debug("token expiration is set at the default value {}", (Object)tokenExpiration);
}
}
public static String buildEncapsulatedToken(String userId) throws CryptoException {
return jwsBuilderFactory.getInstance("HS256").setSubject(userId).setCustomClaimsSetField("scope", (Object)"login").setExpiresIn(tokenExpiration / 1000).build();
}
public static boolean isEncapsulatedToken() {
return encapsulatedToken;
}
protected void bindRepository(SlingRepository slingRepository) {
this.repository = slingRepository;
}
protected void unbindRepository(SlingRepository slingRepository) {
if (this.repository == slingRepository) {
this.repository = null;
}
}
protected void bindSettings(SlingSettingsService slingSettingsService) {
this.settings = slingSettingsService;
}
protected void unbindSettings(SlingSettingsService slingSettingsService) {
if (this.settings == slingSettingsService) {
this.settings = null;
}
}
protected void bindJwsValidator(JwsValidator jwsValidator) {
this.jwsValidator = jwsValidator;
}
protected void unbindJwsValidator(JwsValidator jwsValidator) {
if (this.jwsValidator == jwsValidator) {
this.jwsValidator = null;
}
}
protected void bindConfigAdmin(ConfigurationAdmin configurationAdmin) {
this.configAdmin = configurationAdmin;
}
protected void unbindConfigAdmin(ConfigurationAdmin configurationAdmin) {
if (this.configAdmin == configurationAdmin) {
this.configAdmin = null;
}
}
private class TokenExpirationConfigListener
implements ConfigurationListener {
private TokenExpirationConfigListener() {
}
/*
* WARNING - Removed try catching itself - possible behaviour change.
*/
public void configurationEvent(ConfigurationEvent evt) {
boolean updateTokenExpirationConfig = false;
if (!"org.apache.jackrabbit.oak.security.authentication.token.TokenConfigurationImpl".equals(evt.getPid())) {
return;
}
updateTokenExpirationConfig = true;
ServiceReference ref = evt.getReference();
try {
ConfigurationAdmin ca = (ConfigurationAdmin)TokenAuthenticationHandler.this.context.getService(ref);
if (updateTokenExpirationConfig) {
TokenAuthenticationHandler.this.readTokenExpirationConfig(ca);
}
}
catch (InvalidSyntaxException e) {
TokenAuthenticationHandler.this.log.warn("Error occurred while reading and updating token expiration configuration ", (Throwable)e);
}
catch (IOException e) {
TokenAuthenticationHandler.this.log.warn("Error occurred while reading and updating token expiration configuration ", (Throwable)e);
}
finally {
if (ref != null) {
TokenAuthenticationHandler.this.context.ungetService(ref);
}
}
}
}
}