259.87ba5ef3.js 28.2 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
1
(window.webpackJsonp=window.webpackJsonp||[]).push([[259],{686:function(e,t,a){"use strict";a.r(t);var s=a(56),n=Object(s.a)({},(function(){var e=this,t=e.$createElement,a=e._self._c||t;return a("ContentSlotsDistributor",{attrs:{"slot-key":e.$parent.slotKey}},[a("h1",{attrs:{id:"expression-based-access-control"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#expression-based-access-control"}},[e._v("#")]),e._v(" Expression-Based Access Control")]),e._v(" "),a("h2",{attrs:{id:"overview"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#overview"}},[e._v("#")]),e._v(" Overview")]),e._v(" "),a("p",[e._v('Spring Security uses Spring EL for expression support and you should look at how that works if you are interested in understanding the topic in more depth.\nExpressions are evaluated with a "root object" as part of the evaluation context.\nSpring Security uses specific classes for web and method security as the root object, in order to provide built-in expressions and access to values such as the current principal.')]),e._v(" "),a("h3",{attrs:{id:"common-built-in-expressions"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#common-built-in-expressions"}},[e._v("#")]),e._v(" Common Built-In Expressions")]),e._v(" "),a("p",[e._v("The base class for expression root objects is "),a("code",[e._v("SecurityExpressionRoot")]),e._v(".\nThis provides some common expressions which are available in both web and method security.")]),e._v(" "),a("table",[a("thead",[a("tr",[a("th",[e._v("Expression")]),e._v(" "),a("th",[e._v("Description")])])]),e._v(" "),a("tbody",[a("tr",[a("td",[a("code",[e._v("hasRole(String role)")])]),e._v(" "),a("td",[e._v("Returns "),a("code",[e._v("true")]),e._v(" if the current principal has the specified role."),a("br"),a("br"),e._v("For example, "),a("code",[e._v("hasRole('admin')")]),a("br"),a("br"),e._v("By default if the supplied role does not start with 'ROLE_' it will be added."),a("br"),e._v("This can be customized by modifying the "),a("code",[e._v("defaultRolePrefix")]),e._v(" on "),a("code",[e._v("DefaultWebSecurityExpressionHandler")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("hasAnyRole(String…​ roles)")])]),e._v(" "),a("td",[e._v("Returns "),a("code",[e._v("true")]),e._v(" if the current principal has any of the supplied roles (given as a comma-separated list of strings)."),a("br"),a("br"),e._v("For example, "),a("code",[e._v("hasAnyRole('admin', 'user')")]),a("br"),a("br"),e._v("By default if the supplied role does not start with 'ROLE_' it will be added."),a("br"),e._v("This can be customized by modifying the "),a("code",[e._v("defaultRolePrefix")]),e._v(" on "),a("code",[e._v("DefaultWebSecurityExpressionHandler")]),e._v(".")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("hasAuthority(String authority)")])]),e._v(" "),a("td",[e._v("Returns "),a("code",[e._v("true")]),e._v(" if the current principal has the specified authority."),a("br"),a("br"),e._v("For example, "),a("code",[e._v("hasAuthority('read')")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("hasAnyAuthority(String…​ authorities)")])]),e._v(" "),a("td",[e._v("Returns "),a("code",[e._v("true")]),e._v(" if the current principal has any of the supplied authorities (given as a comma-separated list of strings)"),a("br"),a("br"),e._v("For example, "),a("code",[e._v("hasAnyAuthority('read', 'write')")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("principal")])]),e._v(" "),a("td",[e._v("Allows direct access to the principal object representing the current user")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("authentication")])]),e._v(" "),a("td",[e._v("Allows direct access to the current "),a("code",[e._v("Authentication")]),e._v(" object obtained from the "),a("code",[e._v("SecurityContext")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("permitAll")])]),e._v(" "),a("td",[e._v("Always evaluates to "),a("code",[e._v("true")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("denyAll")])]),e._v(" "),a("td",[e._v("Always evaluates to "),a("code",[e._v("false")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("isAnonymous()")])]),e._v(" "),a("td",[e._v("Returns "),a("code",[e._v("true")]),e._v(" if the current principal is an anonymous user")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("isRememberMe()")])]),e._v(" "),a("td",[e._v("Returns "),a("code",[e._v("true")]),e._v(" if the current principal is a remember-me user")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("isAuthenticated()")])]),e._v(" "),a("td",[e._v("Returns "),a("code",[e._v("true")]),e._v(" if the user is not anonymous")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("isFullyAuthenticated()")])]),e._v(" "),a("td",[e._v("Returns "),a("code",[e._v("true")]),e._v(" if the user is not an anonymous or a remember-me user")])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("hasPermission(Object target, Object permission)")])]),e._v(" "),a("td",[e._v("Returns "),a("code",[e._v("true")]),e._v(" if the user has access to the provided target for the given permission."),a("br"),e._v("For example, "),a("code",[e._v("hasPermission(domainObject, 'read')")])])]),e._v(" "),a("tr",[a("td",[a("code",[e._v("hasPermission(Object targetId, String targetType, Object permission)")])]),e._v(" "),a("td",[e._v("Returns "),a("code",[e._v("true")]),e._v(" if the user has access to the provided target for the given permission."),a("br"),e._v("For example, "),a("code",[e._v("hasPermission(1, 'com.example.domain.Message', 'read')")])])])])]),e._v(" "),a("h2",{attrs:{id:"web-security-expressions"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#web-security-expressions"}},[e._v("#")]),e._v(" Web Security Expressions")]),e._v(" "),a("p",[e._v("To use expressions to secure individual URLs, you would first need to set the "),a("code",[e._v("use-expressions")]),e._v(" attribute in the "),a("code",[e._v("<http>")]),e._v(" element to "),a("code",[e._v("true")]),e._v(".\nSpring Security will then expect the "),a("code",[e._v("access")]),e._v(" attributes of the "),a("code",[e._v("<intercept-url>")]),e._v(" elements to contain Spring EL expressions.\nThe expressions should evaluate to a Boolean, defining whether access should be allowed or not.\nFor example:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("<http>\n\t<intercept-url pattern=\"/admin*\"\n\t\taccess=\"hasRole('admin') and hasIpAddress('192.168.1.0/24')\"/>\n\t...\n</http>\n")])])]),a("p",[e._v('Here we have defined that the "admin" area of an application (defined by the URL pattern) should only be available to users who have the granted authority "admin" and whose IP address matches a local subnet.\nWe’ve already seen the built-in '),a("code",[e._v("hasRole")]),e._v(" expression in the previous section.\nThe expression "),a("code",[e._v("hasIpAddress")]),e._v(" is an additional built-in expression which is specific to web security.\nIt is defined by the "),a("code",[e._v("WebSecurityExpressionRoot")]),e._v(" class, an instance of which is used as the expression root object when evaluating web-access expressions.\nThis object also directly exposed the "),a("code",[e._v("HttpServletRequest")]),e._v(" object under the name "),a("code",[e._v("request")]),e._v(" so you can invoke the request directly in an expression.\nIf expressions are being used, a "),a("code",[e._v("WebExpressionVoter")]),e._v(" will be added to the "),a("code",[e._v("AccessDecisionManager")]),e._v(" which is used by the namespace.\nSo if you aren’t using the namespace and want to use expressions, you will have to add one of these to your configuration.")]),e._v(" "),a("h3",{attrs:{id:"referring-to-beans-in-web-security-expressions"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#referring-to-beans-in-web-security-expressions"}},[e._v("#")]),e._v(" Referring to Beans in Web Security Expressions")]),e._v(" "),a("p",[e._v("If you wish to extend the expressions that are available, you can easily refer to any Spring Bean you expose.\nFor example, assuming you have a Bean with the name of "),a("code",[e._v("webSecurity")]),e._v(" that contains the following method signature:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("public class WebSecurity {\n\t\tpublic boolean check(Authentication authentication, HttpServletRequest request) {\n\t\t\t\t...\n\t\t}\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class WebSecurity {\n    fun check(authentication: Authentication?, request: HttpServletRequest?): Boolean {\n        // ...\n    }\n}\n")])])]),a("p",[e._v("You could refer to the method using:")]),e._v(" "),a("p",[e._v("Example 1. Refer to method")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('http\n    .authorizeHttpRequests(authorize -> authorize\n        .antMatchers("/user/**").access("@webSecurity.check(authentication,request)")\n        ...\n    )\n')])])]),a("p",[e._v("XML")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('<http>\n\t<intercept-url pattern="/user/**"\n\t\taccess="@webSecurity.check(authentication,request)"/>\n\t...\n</http>\n')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('http {\n    authorizeRequests {\n        authorize("/user/**", "@webSecurity.check(authentication,request)")\n    }\n}\n')])])]),a("h3",{attrs:{id:"path-variables-in-web-security-expressions"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#path-variables-in-web-security-expressions"}},[e._v("#")]),e._v(" Path Variables in Web Security Expressions")]),e._v(" "),a("p",[e._v("At times it is nice to be able to refer to path variables within a URL.\nFor example, consider a RESTful application that looks up a user by id from the URL path in the format "),a("code",[e._v("/user/{userId}")]),e._v(".")]),e._v(" "),a("p",[e._v("You can easily refer to the path variable by placing it in the pattern.\nFor example, if you had a Bean with the name of "),a("code",[e._v("webSecurity")]),e._v(" that contains the following method signature:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("public class WebSecurity {\n\t\tpublic boolean checkUserId(Authentication authentication, int id) {\n\t\t\t\t...\n\t\t}\n}\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("class WebSecurity {\n    fun checkUserId(authentication: Authentication?, id: Int): Boolean {\n        // ...\n    }\n}\n")])])]),a("p",[e._v("You could refer to the method using:")]),e._v(" "),a("p",[e._v("Example 2. Path Variables")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('http\n\t.authorizeHttpRequests(authorize -> authorize\n\t\t.antMatchers("/user/{userId}/**").access("@webSecurity.checkUserId(authentication,#userId)")\n\t\t...\n\t);\n')])])]),a("p",[e._v("XML")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('<http>\n\t<intercept-url pattern="/user/{userId}/**"\n\t\taccess="@webSecurity.checkUserId(authentication,#userId)"/>\n\t...\n</http>\n')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('http {\n    authorizeRequests {\n        authorize("/user/{userId}/**", "@webSecurity.checkUserId(authentication,#userId)")\n    }\n}\n')])])]),a("p",[e._v("In this configuration URLs that match would pass in the path variable (and convert it) into checkUserId method.\nFor example, if the URL were "),a("code",[e._v("/user/123/resource")]),e._v(", then the id passed in would be "),a("code",[e._v("123")]),e._v(".")]),e._v(" "),a("h2",{attrs:{id:"method-security-expressions"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#method-security-expressions"}},[e._v("#")]),e._v(" Method Security Expressions")]),e._v(" "),a("p",[e._v("Method security is a bit more complicated than a simple allow or deny rule.\nSpring Security 3.0 introduced some new annotations in order to allow comprehensive support for the use of expressions.")]),e._v(" "),a("h3",{attrs:{id:"pre-and-post-annotations"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#pre-and-post-annotations"}},[e._v("#")]),e._v(" @Pre and @Post Annotations")]),e._v(" "),a("p",[e._v("There are four annotations which support expression attributes to allow pre and post-invocation authorization checks and also to support filtering of submitted collection arguments or return values.\nThey are "),a("code",[e._v("@PreAuthorize")]),e._v(", "),a("code",[e._v("@PreFilter")]),e._v(", "),a("code",[e._v("@PostAuthorize")]),e._v(" and "),a("code",[e._v("@PostFilter")]),e._v(".\nTheir use is enabled through the "),a("code",[e._v("global-method-security")]),e._v(" namespace element:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('<global-method-security pre-post-annotations="enabled"/>\n')])])]),a("h4",{attrs:{id:"access-control-using-preauthorize-and-postauthorize"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#access-control-using-preauthorize-and-postauthorize"}},[e._v("#")]),e._v(" Access Control using @PreAuthorize and @PostAuthorize")]),e._v(" "),a("p",[e._v("The most obviously useful annotation is "),a("code",[e._v("@PreAuthorize")]),e._v(" which decides whether a method can actually be invoked or not.\nFor example (from the "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-security-samples/tree/5.6.x/servlet/xml/java/contacts",target:"_blank",rel:"noopener noreferrer"}},[e._v("Contacts"),a("OutboundLink")],1),e._v(" sample application)")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@PreAuthorize(\"hasRole('USER')\")\npublic void create(Contact contact);\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@PreAuthorize(\"hasRole('USER')\")\nfun create(contact: Contact?)\n")])])]),a("p",[e._v('which means that access will only be allowed for users with the role "ROLE_USER".\nObviously the same thing could easily be achieved using a traditional configuration and a simple configuration attribute for the required role.\nBut what about:')]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@PreAuthorize(\"hasPermission(#contact, 'admin')\")\npublic void deletePermission(Contact contact, Sid recipient, Permission permission);\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@PreAuthorize(\"hasPermission(#contact, 'admin')\")\nfun deletePermission(contact: Contact?, recipient: Sid?, permission: Permission?)\n")])])]),a("p",[e._v('Here we’re actually using a method argument as part of the expression to decide whether the current user has the "admin" permission for the given contact.\nThe built-in '),a("code",[e._v("hasPermission()")]),e._v(" expression is linked into the Spring Security ACL module through the application context, as we’ll "),a("a",{attrs:{href:"#el-permission-evaluator"}},[e._v("see below")]),e._v(".\nYou can access any of the method arguments by name as expression variables.")]),e._v(" "),a("p",[e._v("There are a number of ways in which Spring Security can resolve the method arguments.\nSpring Security uses "),a("code",[e._v("DefaultSecurityParameterNameDiscoverer")]),e._v(" to discover the parameter names.\nBy default, the following options are tried for a method as a whole.")]),e._v(" "),a("ul",[a("li",[a("p",[e._v("If Spring Security’s "),a("code",[e._v("@P")]),e._v(" annotation is present on a single argument to the method, the value will be used.\nThis is useful for interfaces compiled with a JDK prior to JDK 8 which do not contain any information about the parameter names.\nFor example:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import org.springframework.security.access.method.P;\n\n...\n\n@PreAuthorize("#c.name == authentication.name")\npublic void doSomething(@P("c") Contact contact);\n')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import org.springframework.security.access.method.P\n\n...\n\n@PreAuthorize("#c.name == authentication.name")\nfun doSomething(@P("c") contact: Contact?)\n')])])]),a("p",[e._v("Behind the scenes this is implemented using "),a("code",[e._v("AnnotationParameterNameDiscoverer")]),e._v(" which can be customized to support the value attribute of any specified annotation.")])]),e._v(" "),a("li",[a("p",[e._v("If Spring Data’s "),a("code",[e._v("@Param")]),e._v(" annotation is present on at least one parameter for the method, the value will be used.\nThis is useful for interfaces compiled with a JDK prior to JDK 8 which do not contain any information about the parameter names.\nFor example:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import org.springframework.data.repository.query.Param;\n\n...\n\n@PreAuthorize("#n == authentication.name")\nContact findContactByName(@Param("n") String name);\n')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('import org.springframework.data.repository.query.Param\n\n...\n\n@PreAuthorize("#n == authentication.name")\nfun findContactByName(@Param("n") name: String?): Contact?\n')])])]),a("p",[e._v("Behind the scenes this is implemented using "),a("code",[e._v("AnnotationParameterNameDiscoverer")]),e._v(" which can be customized to support the value attribute of any specified annotation.")])]),e._v(" "),a("li",[a("p",[e._v("If JDK 8 was used to compile the source with the -parameters argument and Spring 4+ is being used, then the standard JDK reflection API is used to discover the parameter names.\nThis works on both classes and interfaces.")])]),e._v(" "),a("li",[a("p",[e._v("Last, if the code was compiled with the debug symbols, the parameter names will be discovered using the debug symbols.\nThis will not work for interfaces since they do not have debug information about the parameter names.\nFor interfaces, annotations or the JDK 8 approach must be used.")])])]),e._v(" "),a("p",[e._v("Any Spring-EL functionality is available within the expression, so you can also access properties on the arguments.\nFor example, if you wanted a particular method to only allow access to a user whose username matched that of the contact, you could write")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@PreAuthorize("#contact.name == authentication.name")\npublic void doSomething(Contact contact);\n')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@PreAuthorize("#contact.name == authentication.name")\nfun doSomething(contact: Contact?)\n')])])]),a("p",[e._v("Here we are accessing another built-in expression, "),a("code",[e._v("authentication")]),e._v(", which is the "),a("code",[e._v("Authentication")]),e._v(' stored in the security context.\nYou can also access its "principal" property directly, using the expression '),a("code",[e._v("principal")]),e._v(".\nThe value will often be a "),a("code",[e._v("UserDetails")]),e._v(" instance, so you might use an expression like "),a("code",[e._v("principal.username")]),e._v(" or "),a("code",[e._v("principal.enabled")]),e._v(".")]),e._v(" "),a("p",[e._v("Less commonly, you may wish to perform an access-control check after the method has been invoked.\nThis can be achieved using the "),a("code",[e._v("@PostAuthorize")]),e._v(" annotation.\nTo access the return value from a method, use the built-in name "),a("code",[e._v("returnObject")]),e._v(" in the expression.")]),e._v(" "),a("h4",{attrs:{id:"filtering-using-prefilter-and-postfilter"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#filtering-using-prefilter-and-postfilter"}},[e._v("#")]),e._v(" Filtering using @PreFilter and @PostFilter")]),e._v(" "),a("p",[e._v("Spring Security supports filtering of collections, arrays, maps and streams using expressions.\nThis is most commonly performed on the return value of a method.\nFor example:")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@PreAuthorize(\"hasRole('USER')\")\n@PostFilter(\"hasPermission(filterObject, 'read') or hasPermission(filterObject, 'admin')\")\npublic List<Contact> getAll();\n")])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("@PreAuthorize(\"hasRole('USER')\")\n@PostFilter(\"hasPermission(filterObject, 'read') or hasPermission(filterObject, 'admin')\")\nfun getAll(): List<Contact?>\n")])])]),a("p",[e._v("When using the "),a("code",[e._v("@PostFilter")]),e._v(" annotation, Spring Security iterates through the returned collection or map and removes any elements for which the supplied expression is false.\nFor an array, a new array instance will be returned containing filtered elements.\nThe name "),a("code",[e._v("filterObject")]),e._v(" refers to the current object in the collection.\nIn case when a map is used it will refer to the current "),a("code",[e._v("Map.Entry")]),e._v(" object which allows one to use "),a("code",[e._v("filterObject.key")]),e._v(" or "),a("code",[e._v("filterObject.value")]),e._v(" in the expresion.\nYou can also filter before the method call, using "),a("code",[e._v("@PreFilter")]),e._v(", though this is a less common requirement.\nThe syntax is just the same, but if there is more than one argument which is a collection type then you have to select one by name using the "),a("code",[e._v("filterTarget")]),e._v(" property of this annotation.")]),e._v(" "),a("p",[e._v("Note that filtering is obviously not a substitute for tuning your data retrieval queries.\nIf you are filtering large collections and removing many of the entries then this is likely to be inefficient.")]),e._v(" "),a("h3",{attrs:{id:"built-in-expressions"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#built-in-expressions"}},[e._v("#")]),e._v(" Built-In Expressions")]),e._v(" "),a("p",[e._v("There are some built-in expressions which are specific to method security, which we have already seen in use above.\nThe "),a("code",[e._v("filterTarget")]),e._v(" and "),a("code",[e._v("returnValue")]),e._v(" values are simple enough, but the use of the "),a("code",[e._v("hasPermission()")]),e._v(" expression warrants a closer look.")]),e._v(" "),a("h4",{attrs:{id:"the-permissionevaluator-interface"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#the-permissionevaluator-interface"}},[e._v("#")]),e._v(" The PermissionEvaluator interface")]),e._v(" "),a("p",[a("code",[e._v("hasPermission()")]),e._v(" expressions are delegated to an instance of "),a("code",[e._v("PermissionEvaluator")]),e._v(".\nIt is intended to bridge between the expression system and Spring Security’s ACL system, allowing you to specify authorization constraints on domain objects, based on abstract permissions.\nIt has no explicit dependencies on the ACL module, so you could swap that out for an alternative implementation if required.\nThe interface has two methods:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v("boolean hasPermission(Authentication authentication, Object targetDomainObject,\n\t\t\t\t\t\t\tObject permission);\n\nboolean hasPermission(Authentication authentication, Serializable targetId,\n\t\t\t\t\t\t\tString targetType, Object permission);\n")])])]),a("p",[e._v("which map directly to the available versions of the expression, with the exception that the first argument (the "),a("code",[e._v("Authentication")]),e._v(' object) is not supplied.\nThe first is used in situations where the domain object, to which access is being controlled, is already loaded.\nThen expression will return true if the current user has the given permission for that object.\nThe second version is used in cases where the object is not loaded, but its identifier is known.\nAn abstract "type" specifier for the domain object is also required, allowing the correct ACL permissions to be loaded.\nThis has traditionally been the Java class of the object, but does not have to be as long as it is consistent with how the permissions are loaded.')]),e._v(" "),a("p",[e._v("To use "),a("code",[e._v("hasPermission()")]),e._v(" expressions, you have to explicitly configure a "),a("code",[e._v("PermissionEvaluator")]),e._v(" in your application context.\nThis would look something like this:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('<security:global-method-security pre-post-annotations="enabled">\n<security:expression-handler ref="expressionHandler"/>\n</security:global-method-security>\n\n<bean id="expressionHandler" class=\n"org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">\n\t<property name="permissionEvaluator" ref="myPermissionEvaluator"/>\n</bean>\n')])])]),a("p",[e._v("Where "),a("code",[e._v("myPermissionEvaluator")]),e._v(" is the bean which implements "),a("code",[e._v("PermissionEvaluator")]),e._v(".\nUsually this will be the implementation from the ACL module which is called "),a("code",[e._v("AclPermissionEvaluator")]),e._v(".\nSee the "),a("a",{attrs:{href:"https://github.com/spring-projects/spring-security-samples/tree/5.6.x/servlet/xml/java/contacts",target:"_blank",rel:"noopener noreferrer"}},[e._v("Contacts"),a("OutboundLink")],1),e._v(" sample application configuration for more details.")]),e._v(" "),a("h4",{attrs:{id:"method-security-meta-annotations"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#method-security-meta-annotations"}},[e._v("#")]),e._v(" Method Security Meta Annotations")]),e._v(" "),a("p",[e._v("You can make use of meta annotations for method security to make your code more readable.\nThis is especially convenient if you find that you are repeating the same complex expression throughout your code base.\nFor example, consider the following:")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@PreAuthorize("#contact.name == authentication.name")\n')])])]),a("p",[e._v("Instead of repeating this everywhere, we can create a meta annotation that can be used instead.")]),e._v(" "),a("p",[e._v("Java")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Retention(RetentionPolicy.RUNTIME)\n@PreAuthorize("#contact.name == authentication.name")\npublic @interface ContactPermission {}\n')])])]),a("p",[e._v("Kotlin")]),e._v(" "),a("div",{staticClass:"language- extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[e._v('@Retention(AnnotationRetention.RUNTIME)\n@PreAuthorize("#contact.name == authentication.name")\nannotation class ContactPermission\n')])])]),a("p",[e._v("Meta annotations can be used for any of the Spring Security method security annotations.\nIn order to remain compliant with the specification JSR-250 annotations do not support meta annotations.")]),e._v(" "),a("p",[a("RouterLink",{attrs:{to:"/en/spring-security/authorize-requests.html"}},[e._v("Authorize HTTP Requests with FilterSecurityInterceptor")]),a("RouterLink",{attrs:{to:"/en/spring-security/secure-objects.html"}},[e._v("Secure Object Implementations")])],1)])}),[],!1,null,null,null);t.default=n.exports}}]);