Spring Spel for roles - spring

I have a custom requirement where I want to decide if an API can be accessed depending on certain roles. I am using Spring framework.
I want to support something like this:
1. (R1 || R2) && (R3 || R4)
2. (R1) || (R2 && R3)
where R represents a role. || and && are logical operators denoting or and and respectively.
This expression should be evaluated against an input array of roles.
So if the input array is [R2, R4], then the first expression evaluates to true and second expression evaluates to false.
I found something similar using SPEL but instead of R which can be any String like customer, employee, etc, they are using boolean expressions value like true or 6 == 6, etc

You can use method security based on roles with SpEL.
#PreAuthorize("hasRole('ROLE_A') or hasRole('ROLE_B')")
public void yourMethod() {
// ...
}

I solved the above problem using the following:
I used SpEL as provided by Spring.
SpEL supports property replacement.
Code for replacement:
Inventor tesla = new Inventor("Nikola Tesla");
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("name == Nikola Tesla");
String name = (String) exp.getValue(tesla);
Here, the name property will be replaced by Nikola Tesla.
This should be used when the name property has different value each time the expression is evaluated.
If the value of name property is the same every time, consider using EvaluationContext.
Now talking about the boolean expressions, you will have to compulsorily substitute values for properties, because in above example, property name can take null as the default value, but a string role can't take true or false without substitution.
And let's suppose that the SpEL contains some roles which I am not aware of, I won't be able to replace them with true and false. To solve this, I used something similar to #PreAuthorize which has the method hasRole().
Code for reference:
String roles = "(hasRole('admin') or hasRole('superAdmin')) and hasRole('modifier')"
Expression roleExpression = parser.parseExpression(roles);
StandardEvaluationContext roleContext = new StandardEvaluationContext(new SpelHelper());
roleContext.addPropertyAccessor(new MapAccessor()); // this line might be useless
Boolean hasCorrectRole = roleExpression.getValue(roleContext, Boolean.class);
class SpelHelper {
public boolean hasRole(String role) {
// some logic like current user roles have the role passed as argument
return true;
}
}
Full documentation at:
https://docs.spring.io/spring/docs/4.0.x/spring-framework-reference/html/expressions.html
Also, refer Boolean Expression Evaluation in Java
This answer suggests using JEXL and the answer will give you a fair idea what to do to replace properties.

Related

Eliminating vurnabilities in the Spring SpEL

I'm testing the Spring SpEL and I thinking if it is possible to somehow limit what kind of SpEL query can be provided, to avoid some unwanted code injection? I just want to get values from some object, so is it possible to block other types of operations? I can't find such functionality in the Spring documentation.
For instance, I just want to allow to check if the value from the test object equals XYZ.
Test test = new Test("XYZ", 999);
ExpressionParser expressionParser = new SpelExpressionParser();
Expression expression = expressionParser.parseExpression("value eq 'XYZ'");
System.out.println(expression.getValue(new StandardEvaluationContext(test)));
However, I would like to limit which expressions are valid. I don't what to evaluate expressions which allow to execute some code, for instance:
Expression expression = expressionParser.parseExpression("''.getClass().forName('java.lang.Runtime').getMethods()[6]");
As #ArtemBilan mentioned in the comment, the solution to limit the SpEL language syntax and eliminate unwanted code execution is to use the SimpleEvaluationContext class, for instance:
SimpleEvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding()
.withInstanceMethods()
.withRootObject(test)
.build();

Getting and Setting values in java 8 using optional and map

I am trying to use Optional instead of standard null checks in java
#Data
public class InputObj {
private Double savings;
}
#Data
public class Result {
private String outputSavings;
}
public Result convertInputObjToResult(InputObj inputObj){
Result result = new Result();
Optional<InputObj> optionalInputObj = Optional.ofNullable(inputObj);
optionalInputObj.map(InputObj::getSavings).map(value -> util.convertRoundAndAbs(value,true)).ifPresent(result::setOutputSavings);
return result;
}
which is equivalent of below
public Result convertInputObjToResult(InputObj inputObj){
Result result = new Result();
if(inputObj != null){
if(inputObj.getSavings() != null){
result.setOutputSavings(util.convertRoundAndAbs(inputObj.getSavings(),true));
}
}
return result;
}
I wrote some test cases and I do not get any Null Pointer Exception but I am unable to understand that ifPresent condition is at end and map is before but still I don't get any NPE. Do you see any thing wrong with this code or how it can be improved? This is part of a spring boot application and #Data annotation is used for lombok.
Here's a link to further describe how the map operation works for the Java Optional class.
If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.
So in a case where you have a null value from the map method, it will automatically be converted to Optional.empty().
Then, taking a look at the ifPresent method
If a value is present, invoke the specified consumer with the value, otherwise do nothing.
So this is why you aren't getting any NPE's; the map operations are able to map null results or passed values to Optional.empty(), and the ifPresent operation doesn't execute if passed an empty Optional.
There is no issue with the code except for the typo “ optionalMembershipDetails”. Assuming you meant to use “ optionalInputObj”.
You need to read about java streams to understand the full concept. In a nutshell, operations are evaluated in lazy manner. So ifPresent call will trigger operations which appear before it. In this case, the object is wrapped inside optional, so each intermediate operation will pass another optional to the next operation. Having Optional prevents you getting NPE.

Why cant nullable arrays/hashmaps be accessed using []

When I have a nullable array/list/hashmap such as
var x: ArrayList<String>? = null
I know can access the element at index 1 like so
var element = x?.get(1)
or I could do it in a unsafe way like this
var element = x!![1]
but why can't I do something like this
var element = x?[1]
what's the difference between getting elements from an array using the first example and the last example, and why is the last example not allowed?
In the first example, you're using the safe call operator ?. to call the get function with it.
In the second example, you're using the [] operator on the non-nullable return value of the x!! expression, which of course is allowed.
However, the language simply doesn't have a ?[] operator, which would be the combination of the two. The other operators offered are also don't have null-safe variants: there's no ?+ or ?&& or anything like that. This is just a design decision by the language creators. (The full list of available operators is here).
If you want to use operators, you need to call them on non-nullable expressions - only functions get the convenience of the safe call operator.
You could also define your own operator as an extension of the nullable type:
operator fun <T> List<T>?.get(index: Int) = this?.get(index)
val x: ArrayList<String>? = null
val second = x[2] // null
This would get you a neater syntax, but it hides the underlying null handling, and might confuse people who don't expect this custom extension on collections.

Checking, if optional parameter is provided in Dart

I'm new to Dart and just learning the basics.
The Dart-Homepage shows following:
It turns out that Dart does indeed have a way to ask if an optional
parameter was provided when the method was called. Just use the
question mark parameter syntax.
Here is an example:
void alignDingleArm(num axis, [num rotations]) {
if (?rotations) {
// the parameter was really used
}
}
So I've wrote a simple testing script for learning:
import 'dart:html';
void main() {
String showLine(String string, {String printBefore : "Line: ", String printAfter}){
// check, if parameter was set manually:
if(?printBefore){
// check, if parameter was set to null
if(printBefore == null){
printBefore = "";
}
}
String line = printBefore + string + printAfter;
output.appendText(line);
output.appendHtml("<br />\n");
return line;
}
showLine("Hallo Welt!",printBefore: null);
}
The Dart-Editor already marks the questionmark as Error:
Multiple markers at this line
- Unexpected token '?'
- Conditions must have a static type of
'bool'
When running the script in Dartium, the JS-Console shows folloing Error:
Internal error: 'http://localhost:8081/main.dart': error: line 7 pos 8: unexpected token '?'
if(?printBefore){
^
I know, that it would be enough to check if printBefore is null, but I want to learn the language.
Does anyone know the reason for this problem?
How to check, if the parameter is set manually?
The feature existed at some point in Dart's development, but it was removed again because it caused more complication than it removed, without solving the problem that actually needed solving - forwarding of default parameters.
If you have a function foo([x = 42]) and you want a function to forward to it, bar([x]) => f(x);, then, since foo could actually tell if x is passed or not, you actually ended up writing bar([x]) => ?x ? foo(x) : foo();. That was worse than what you had to do without the ?: operator.
Ideas came up about having a bar([x]) => foo(?:x) or something which pased on x if it was present and not if it was absent (I no longer remember the actual proposed syntax), but that got complicated fast, fx converting named arguments to positional - bar({x,y}) => foo(?:x, ?:y); - what if y was provided and x was not. It was really just a bad solution for a self-inflicted problem.
So, the ?x feature was rolled back. All optional parameters have a default value which is passed if there is no matching argument in a call. If you want to forward an optional parameter, you need to know the default value of the function you are forwarding to.
For most function arguments, the declared default value is null, with an internal if (arg == null) arg = defaultValue; statement to fix it. That means that the null value can be forwarded directly without any confusion.
Some arguments have a non-null default value. It's mostly boolean arguments, but there are other cases too. I recommend using null for everything except named boolean parameters (because they are really meant to be named more than they are meant to be optional). At least unless there is a good reason not to - like ensuring that all subclasses will have the same default value for a method parameter (which may be a good reason, or not, and should be used judiciosuly).
If you have an optional parameter that can also accept null as a value ... consider whether it should really be optional, or if you just need a different function with one more argument. Or maybe you can introduce a different "missing argument" default value. Example:
abstract class C { foo([D something]); }
class _DMarker implements D { const _DMarker(); }
class _ActualC {
foo([D something = const _DMarker()]) {
if (something == const _DMarker()) {
// No argument passed, because user cannot create a _DMarker.
} else {
// Argument passed, may be null.
}
}
}
This is a big workaround, and hardly ever worth it. In general, just use null as default value, it's simpler.
I was trying something similar:
This does not work
widget.optionalStringParameter ? widget.optionalStringParameter : 'default string'
This works
widget.optionalStringParameter != null ? widget.optionalStringParameter : 'default string'
This also works
widget.optionalStringParameter ?? 'default string'
There was support for checking if an optional parameter was actually provider in early Dart days (pre 1.0) but was removed because it causes some troubles.

How do I combine LINQ expressions into one?

I've got a form with multiple fields on it (company name, postcode, etc.) which allows a user to search for companies in a database. If the user enters values in more than one field then I need to search on all of those fields. I am using LINQ to query the database.
So far I have managed to write a function which will look at their input and turn it into a List of expressions. I now want to turn that List into a single expression which I can then execute via the LINQ provider.
My initial attempt was as follows
private Expression<Func<Company, bool>> Combine(IList<Expression<Func<Company, bool>>> expressions)
{
if (expressions.Count == 0)
{
return null;
}
if (expressions.Count == 1)
{
return expressions[0];
}
Expression<Func<Company, bool>> combined = expressions[0];
expressions.Skip(1).ToList().ForEach(expr => combined = Expression.And(combined, expr));
return combined;
}
However this fails with an exception message along the lines of "The binary operator And is not defined for...". Does anyone have any ideas what I need to do to combine these expressions?
EDIT: Corrected the line where I had forgotten to assign the result of and'ing the expressions together to a variable. Thanks for pointing that out folks.
You can use Enumerable.Aggregate combined with Expression.AndAlso. Here's a generic version:
Expression<Func<T, bool>> AndAll<T>(
IEnumerable<Expression<Func<T, bool>>> expressions) {
if(expressions == null) {
throw new ArgumentNullException("expressions");
}
if(expressions.Count() == 0) {
return t => true;
}
Type delegateType = typeof(Func<,>)
.GetGenericTypeDefinition()
.MakeGenericType(new[] {
typeof(T),
typeof(bool)
}
);
var combined = expressions
.Cast<Expression>()
.Aggregate((e1, e2) => Expression.AndAlso(e1, e2));
return (Expression<Func<T,bool>>)Expression.Lambda(delegateType, combined);
}
Your current code is never assigning to combined:
expr => Expression.And(combined, expr);
returns a new Expression that is the result of bitwise anding combined and expr but it does not mutate combined.
EDIT: Jason's answer is now fuller than mine was in terms of the expression tree stuff, so I've removed that bit. However, I wanted to leave this:
I assume you're using these for a Where clause... why not just call Where with each expression in turn? That should have the same effect:
var query = ...;
foreach (var condition in conditions)
{
query = query.Where(condition);
}
Here we have a general question about combining Linq expressions. I have a general solution for this problem. I will provide an answer regarding the specific problem posted, although it's definitely not the way to go in such cases. But when simple solutions fail in your case, you may try to use this approach.
First you need a library consisting of 2 simple functions. They use System.Linq.Expressions.ExpressionVisitor to dynamically modify expressions. The key feature is unifying parameters inside the expression, so that 2 parameters with the same name were made identical (UnifyParametersByName). The remaining part is replacing a named parameter with given expression (ReplacePar). The library is available with MIT license on github: LinqExprHelper, but you may quickly write something on your own.
The library allows for quite simple syntax for combining complex expressions. You can mix inline lambda expressions, which are nice to read, together with dynamic expression creation and composition, which is very capable.
private static Expression<Func<Company, bool>> Combine(IList<Expression<Func<Company, bool>>> expressions)
{
if (expressions.Count == 0)
{
return null;
}
// Prepare a master expression, used to combine other
// expressions. It needs more input parameters, they will
// be reduced later.
// There is a small inconvenience here: you have to use
// the same name "c" for the parameter in your input
// expressions. But it may be all done in a smarter way.
Expression <Func<Company, bool, bool, bool>> combiningExpr =
(c, expr1, expr2) => expr1 && expr2;
LambdaExpression combined = expressions[0];
foreach (var expr in expressions.Skip(1))
{
// ReplacePar comes from the library, it's an extension
// requiring `using LinqExprHelper`.
combined = combiningExpr
.ReplacePar("expr1", combined.Body)
.ReplacePar("expr2", expr.Body);
}
return (Expression<Func<Company, bool>>)combined;
}
Assume you have two expression e1 and e2, you can try this:
var combineBody = Expression.AndAlso(e1.Body, Expression.Invoke(e2, e1.Parameters[0]));
var finalExpression = Expression.Lambda<Func<TestClass, bool>>(combineBody, e1.Parameters).Compile();

Resources