|
| 1 | +/* |
| 2 | + * Copyright 2002-2024 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.authorization.method; |
| 18 | + |
| 19 | +import org.springframework.expression.EvaluationContext; |
| 20 | +import org.springframework.expression.EvaluationException; |
| 21 | +import org.springframework.expression.Expression; |
| 22 | +import org.springframework.security.authorization.AuthorizationResult; |
| 23 | +import org.springframework.security.authorization.ExpressionAuthorizationDecision; |
| 24 | + |
| 25 | +final class ExpressionUtils { |
| 26 | + |
| 27 | + private ExpressionUtils() { |
| 28 | + } |
| 29 | + |
| 30 | + static AuthorizationResult evaluate(Expression expr, EvaluationContext ctx) { |
| 31 | + try { |
| 32 | + Object result = expr.getValue(ctx); |
| 33 | + if (result instanceof AuthorizationResult decision) { |
| 34 | + return decision; |
| 35 | + } |
| 36 | + if (result instanceof Boolean granted) { |
| 37 | + return new ExpressionAuthorizationDecision(granted, expr); |
| 38 | + } |
| 39 | + if (result == null) { |
| 40 | + return null; |
| 41 | + } |
| 42 | + throw new IllegalArgumentException( |
| 43 | + "SpEL expression must return either a Boolean or an AuthorizationDecision"); |
| 44 | + } |
| 45 | + catch (EvaluationException ex) { |
| 46 | + throw new IllegalArgumentException("Failed to evaluate expression '" + expr.getExpressionString() + "'", |
| 47 | + ex); |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | +} |
0 commit comments