|
| 1 | +/* |
| 2 | + * Copyright 2002-2022 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.security.web.context; |
| 18 | + |
| 19 | +import java.util.function.Supplier; |
| 20 | + |
| 21 | +import org.apache.commons.logging.Log; |
| 22 | +import org.apache.commons.logging.LogFactory; |
| 23 | + |
| 24 | +import org.springframework.core.log.LogMessage; |
| 25 | +import org.springframework.security.core.context.DeferredSecurityContext; |
| 26 | +import org.springframework.security.core.context.SecurityContext; |
| 27 | +import org.springframework.security.core.context.SecurityContextHolderStrategy; |
| 28 | + |
| 29 | +/** |
| 30 | + * @author Steve Riesenberg |
| 31 | + * @since 5.8 |
| 32 | + */ |
| 33 | +final class SupplierDeferredSecurityContext implements DeferredSecurityContext { |
| 34 | + |
| 35 | + private static final Log logger = LogFactory.getLog(SupplierDeferredSecurityContext.class); |
| 36 | + |
| 37 | + private final Supplier<SecurityContext> supplier; |
| 38 | + |
| 39 | + private final SecurityContextHolderStrategy strategy; |
| 40 | + |
| 41 | + private SecurityContext securityContext; |
| 42 | + |
| 43 | + private boolean missingContext; |
| 44 | + |
| 45 | + SupplierDeferredSecurityContext(Supplier<SecurityContext> supplier, SecurityContextHolderStrategy strategy) { |
| 46 | + this.supplier = supplier; |
| 47 | + this.strategy = strategy; |
| 48 | + } |
| 49 | + |
| 50 | + @Override |
| 51 | + public SecurityContext get() { |
| 52 | + init(); |
| 53 | + return this.securityContext; |
| 54 | + } |
| 55 | + |
| 56 | + @Override |
| 57 | + public boolean isGenerated() { |
| 58 | + init(); |
| 59 | + return this.missingContext; |
| 60 | + } |
| 61 | + |
| 62 | + private void init() { |
| 63 | + if (this.securityContext != null) { |
| 64 | + return; |
| 65 | + } |
| 66 | + |
| 67 | + this.securityContext = this.supplier.get(); |
| 68 | + this.missingContext = (this.securityContext == null); |
| 69 | + if (this.missingContext) { |
| 70 | + this.securityContext = this.strategy.createEmptyContext(); |
| 71 | + if (logger.isTraceEnabled()) { |
| 72 | + logger.trace(LogMessage.format("Created %s", this.securityContext)); |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | +} |
0 commit comments