How to prevent “SQL Injection” in Core Data?

百般思念 提交于 2019-12-04 04:16:56

问题


I am building a pretty complex predicate in several iterations, and want to supply the matching values right away in the predicate.

Instead of:

[NSPredicate predicateWithFormat:@"departmentName like[c] %@"];

I want to do:

NSString *str = [NSString stringWithFormat:@"departmentName like[c] '%@'", departmentName]; [NSPredicate predicateWithFormat:str];

Since this is a dumb substitution, I guess it's possible to "hack" the predicate accidently by entering garbage.

I couldn't find anything that would "magically quote" that value for me.

Reason is, that I need to build up a complex predicate in several iterations, so I have to construct a big predicate string. Templates don't work with SUBQUERY. So I need to provide the values right away in the string, since I don't want to make 20 different predicate initializations depending on how many values I have for the predicate format.


回答1:


Use NSComparisonPredicate directly, and bypass the predicate format issues.

NSPredicate *fetchPredicate = [NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"departmentName"]
                                                                 rightExpression:[NSExpression expressionForConstantValue:searchTerm]
                                                                        modifier:NSDirectPredicateModifier
                                                                            type:NSLikePredicateOperatorType
                                                                         options:0];

Have a read through the Predicate Programming Guide "Creating Predicates Directly in Code", and check the class reference for NSComparisonPredicate



来源:https://stackoverflow.com/questions/3076894/how-to-prevent-sql-injection-in-core-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!