diff --git a/docs/modules/ROOT/assets/images/servlet/authorization/methodsecurity.odg b/docs/modules/ROOT/assets/images/servlet/authorization/methodsecurity.odg new file mode 100644 index 0000000000..8b5ffa6801 Binary files /dev/null and b/docs/modules/ROOT/assets/images/servlet/authorization/methodsecurity.odg differ diff --git a/docs/modules/ROOT/assets/images/servlet/authorization/methodsecurity.png b/docs/modules/ROOT/assets/images/servlet/authorization/methodsecurity.png new file mode 100644 index 0000000000..fd5d140d6d Binary files /dev/null and b/docs/modules/ROOT/assets/images/servlet/authorization/methodsecurity.png differ diff --git a/docs/modules/ROOT/nav.adoc b/docs/modules/ROOT/nav.adoc index c5db68ab81..d465c3a1f8 100644 --- a/docs/modules/ROOT/nav.adoc +++ b/docs/modules/ROOT/nav.adoc @@ -59,9 +59,7 @@ ** xref:servlet/authorization/index.adoc[Authorization] *** xref:servlet/authorization/architecture.adoc[Authorization Architecture] *** xref:servlet/authorization/authorize-http-requests.adoc[Authorize HTTP Requests] -*** xref:servlet/authorization/authorize-requests.adoc[Authorize HTTP Requests with FilterSecurityInterceptor] *** xref:servlet/authorization/expression-based.adoc[Expression-Based Access Control] -*** xref:servlet/authorization/secure-objects.adoc[Secure Object Implementations] *** xref:servlet/authorization/method-security.adoc[Method Security] *** xref:servlet/authorization/acls.adoc[Domain Object Security ACLs] *** xref:servlet/authorization/events.adoc[Authorization Events] diff --git a/docs/modules/ROOT/pages/migration/servlet/authorization.adoc b/docs/modules/ROOT/pages/migration/servlet/authorization.adoc index c77f2bd589..95b22ed5f8 100644 --- a/docs/modules/ROOT/pages/migration/servlet/authorization.adoc +++ b/docs/modules/ROOT/pages/migration/servlet/authorization.adoc @@ -36,7 +36,7 @@ There are no further migrations steps for Java or Kotlin for this feature. == Use `AuthorizationManager` for Request Security In 6.0, `` defaults `once-per-request` to `false`, `filter-all-dispatcher-types` to `true`, and `use-authorization-manager` to `true`. -Also, xref:servlet/authorization/authorize-requests.adoc#filtersecurityinterceptor-every-request[`authorizeRequests#filterSecurityInterceptorOncePerRequest`] defaults to `false` and xref:servlet/authorization/authorize-http-requests.adoc[`authorizeHttpRequests#filterAllDispatcherTypes`] defaults to `true`. +Also, {security-api-url}org/springframework/security/config/annotation/web/configurers/AbstractInterceptUrlConfigurer.AbstractInterceptUrlRegistry.html#filterSecurityInterceptorOncePerRequest(boolean)[`authorizeRequests#filterSecurityInterceptorOncePerRequest`] defaults to `false` and xref:servlet/authorization/authorize-http-requests.adoc[`authorizeHttpRequests#filterAllDispatcherTypes`] defaults to `true`. So, to complete migration, any defaults values can be removed. For example, if you opted in to the 6.0 default for `filter-all-dispatcher-types` or `authorizeHttpRequests#filterAllDispatcherTypes` like so: diff --git a/docs/modules/ROOT/pages/servlet/architecture.adoc b/docs/modules/ROOT/pages/servlet/architecture.adoc index 36b8d2520c..b804f6405b 100644 --- a/docs/modules/ROOT/pages/servlet/architecture.adoc +++ b/docs/modules/ROOT/pages/servlet/architecture.adoc @@ -194,7 +194,7 @@ The following is a comprehensive list of Spring Security Filter ordering: * `OAuth2AuthorizationCodeGrantFilter` * `SessionManagementFilter` * <> -* xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] +* xref:servlet/authorization/authorize-http-requests.adoc[`AuthorizationFilter`] * `SwitchUserFilter` [[servlet-exceptiontranslationfilter]] diff --git a/docs/modules/ROOT/pages/servlet/authentication/passwords/basic.adoc b/docs/modules/ROOT/pages/servlet/authentication/passwords/basic.adoc index 7c84277062..9eba5df7f1 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/passwords/basic.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/passwords/basic.adoc @@ -15,7 +15,7 @@ The preceding figure builds off our xref:servlet/architecture.adoc#servlet-secur image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the resource `/private` for which it is not authorized. -image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] indicates that the unauthenticated request is __Denied__ by throwing an `AccessDeniedException`. +image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-http-requests.adoc[`AuthorizationFilter`] indicates that the unauthenticated request is __Denied__ by throwing an `AccessDeniedException`. image:{icondir}/number_3.png[] Since the user is not authenticated, xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates __Start Authentication__. The configured xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is an instance of {security-api-url}org/springframework/security/web/authentication/www/BasicAuthenticationEntryPoint.html[`BasicAuthenticationEntryPoint`], which sends a WWW-Authenticate header. diff --git a/docs/modules/ROOT/pages/servlet/authentication/passwords/form.adoc b/docs/modules/ROOT/pages/servlet/authentication/passwords/form.adoc index 7961352430..95c00337f8 100644 --- a/docs/modules/ROOT/pages/servlet/authentication/passwords/form.adoc +++ b/docs/modules/ROOT/pages/servlet/authentication/passwords/form.adoc @@ -16,7 +16,7 @@ The preceding figure builds off our xref:servlet/architecture.adoc#servlet-secur image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the resource (`/private`) for which it is not authorized. -image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] indicates that the unauthenticated request is __Denied__ by throwing an `AccessDeniedException`. +image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-http-requests.adoc[`AuthorizationFilter`] indicates that the unauthenticated request is __Denied__ by throwing an `AccessDeniedException`. image:{icondir}/number_3.png[] Since the user is not authenticated, xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates __Start Authentication__ and sends a redirect to the login page with the configured xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`]. In most cases, the `AuthenticationEntryPoint` is an instance of {security-api-url}org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.html[`LoginUrlAuthenticationEntryPoint`]. diff --git a/docs/modules/ROOT/pages/servlet/authorization/architecture.adoc b/docs/modules/ROOT/pages/servlet/authorization/architecture.adoc index 5eaf5b1e85..04292720b8 100644 --- a/docs/modules/ROOT/pages/servlet/authorization/architecture.adoc +++ b/docs/modules/ROOT/pages/servlet/authorization/architecture.adoc @@ -23,30 +23,76 @@ String getAuthority(); ---- ==== -This method lets an -`AccessDecisionManager` instance to obtain a precise `String` representation of the `GrantedAuthority`. -By returning a representation as a `String`, a `GrantedAuthority` can be easily "`read`" by most `AccessDecisionManager` implementations. -If a `GrantedAuthority` cannot be precisely represented as a `String`, the `GrantedAuthority` is considered "`complex`" and `getAuthority()` must return `null`. +This method is used by an +`AuthorizationManager` instance to obtain a precise `String` representation of the `GrantedAuthority`. +By returning a representation as a `String`, a `GrantedAuthority` can be easily "read" by most `AuthorizationManager` implementations. +If a `GrantedAuthority` cannot be precisely represented as a `String`, the `GrantedAuthority` is considered "complex" and `getAuthority()` must return `null`. -An example of a "`complex`" `GrantedAuthority` would be an implementation that stores a list of operations and authority thresholds that apply to different customer account numbers. +An example of a complex `GrantedAuthority` would be an implementation that stores a list of operations and authority thresholds that apply to different customer account numbers. Representing this complex `GrantedAuthority` as a `String` would be quite difficult. As a result, the `getAuthority()` method should return `null`. -This indicates to any `AccessDecisionManager` that it needs to support the specific `GrantedAuthority` implementation to understand its contents. +This indicates to any `AuthorizationManager` that it needs to support the specific `GrantedAuthority` implementation to understand its contents. Spring Security includes one concrete `GrantedAuthority` implementation: `SimpleGrantedAuthority`. This implementation lets any user-specified `String` be converted into a `GrantedAuthority`. All `AuthenticationProvider` instances included with the security architecture use `SimpleGrantedAuthority` to populate the `Authentication` object. +[[jc-method-security-custom-granted-authority-defaults]] +By default, role-based authorization rules include `ROLE_` as a prefix. +This means that if there is an authorization rule that requires a security context to have a role of "USER", Spring Security will by default look for a `GrantedAuthority#getAuthority` that returns "ROLE_USER". + +You can customize this with `GrantedAuthorityDefaults`. +`GrantedAuthorityDefaults` exists to allow customizing the prefix to use for role-based authorization rules. + +You can configure the authorization rules to use a different prefix by exposing a `GrantedAuthorityDefaults` bean, like so: + +.Custom MethodSecurityExpressionHandler +==== +.Java +[source,java,role="primary"] +---- +@Bean +static GrantedAuthorityDefaults grantedAuthorityDefaults() { + return new GrantedAuthorityDefaults("MYPREFIX_"); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +companion object { + @Bean + fun grantedAuthorityDefaults() : GrantedAuthorityDefaults { + return GrantedAuthorityDefaults("MYPREFIX_"); + } +} +---- + +.Xml +[source,xml,role="secondary"] +---- + + + +---- +==== + +[TIP] +==== +You expose `GrantedAuthorityDefaults` using a `static` method to ensure that Spring publishes it before it initializes Spring Security's method security `@Configuration` classes +==== + [[authz-pre-invocation]] -== Pre-Invocation Handling +== Invocation Handling Spring Security provides interceptors that control access to secure objects, such as method invocations or web requests. -A pre-invocation decision on whether the invocation is allowed to proceed is made by the `AccessDecisionManager`. +A pre-invocation decision on whether the invocation is allowed to proceed is made by `AuthorizationManager` instances. +Also post-invocation decisions on whether a given value may be returned is made by `AuthorizationManager` instances. === The AuthorizationManager `AuthorizationManager` supersedes both <>. Applications that customize an `AccessDecisionManager` or `AccessDecisionVoter` are encouraged to <>. -``AuthorizationManager``s are called by the xref:servlet/authorization/authorize-http-requests.adoc[`AuthorizationFilter`] and are responsible for making final access control decisions. +``AuthorizationManager``s are called by Spring Security's xref:servlet/authorization/authorize-http-requests.adoc[request-based], xref:servlet/authorization/method-security.adoc[method-based], and xref:servlet/integrations/websocket.adoc[message-based] authorization components and are responsible for making final access control decisions. The `AuthorizationManager` interface contains two methods: ==== @@ -97,6 +143,10 @@ Another manager is the `AuthenticatedAuthorizationManager`. It can be used to differentiate between anonymous, fully-authenticated and remember-me authenticated users. Many sites allow certain limited access under remember-me authentication, but require a user to confirm their identity by logging in for full access. +[[authz-authorization-managers]] +==== AuthorizationManagers +There are also helpful static factories in `AuthenticationManagers` for composing individual ``AuthenticationManager``s into more sophisticated expressions. + [[authz-custom-authorization-manager]] ==== Custom Authorization Managers Obviously, you can also implement a custom `AuthorizationManager` and you can put just about any access-control logic you want in it. diff --git a/docs/modules/ROOT/pages/servlet/authorization/authorize-http-requests.adoc b/docs/modules/ROOT/pages/servlet/authorization/authorize-http-requests.adoc index 72d720b329..c0514e4ad2 100644 --- a/docs/modules/ROOT/pages/servlet/authorization/authorize-http-requests.adoc +++ b/docs/modules/ROOT/pages/servlet/authorization/authorize-http-requests.adoc @@ -1,11 +1,737 @@ [[servlet-authorization-authorizationfilter]] -= Authorize HttpServletRequests with AuthorizationFilter += Authorize HttpServletRequests :figures: servlet/authorization -This section builds on xref:servlet/architecture.adoc#servlet-architecture[Servlet Architecture and Implementation] by digging deeper into how xref:servlet/authorization/index.adoc#servlet-authorization[authorization] works within Servlet-based applications. +Spring Security allows you to xref:servlet/authorization/index.adoc[model your authorization] at the request level. +For example, with Spring Security you can say that all pages under `/admin` require one authority while all other pages simply require authentication. + +By default, Spring Security requires that every request be authenticated. +That said, any time you use xref:servlet/configuration/java.adoc#jc-httpsecurity[an `HttpSecurity` instance], it's necessary to declare your authorization rules. + +[[activate-request-security]] +Whenever you have an `HttpSecurity` instance, you should at least do: + +.Use authorizeHttpRequests +==== +.Java +[source,java,role="primary"] +---- +http + .authorizeHttpRequests((authorize) -> authorize + .anyRequest().authenticated() + ) +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +http { + authorizeHttpRequests { + authorize(anyRequest, authenticated) + } +} +---- + +.Xml +[source,xml,role="secondary"] +---- + + + +---- +==== + +This tells Spring Security that any endpoint in your application requires that the security context at a minimum be authenticated in order to allow it. + +In many cases, your authorization rules will be more sophisticated than that, so please consider the following use cases: + +* I have an app that uses `authorizeRequests` and I want to <> +* I want to <> +* I want to <> based on a pattern; specifically <> +* I want to <> +* I want to <> +* I want to <> +* I want to <> to a policy agent + +[[request-authorization-architecture]] +== Understanding How Request Authorization Components Work [NOTE] -`AuthorizationFilter` supersedes xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`]. +This section builds on xref:servlet/architecture.adoc#servlet-architecture[Servlet Architecture and Implementation] by digging deeper into how xref:servlet/authorization/index.adoc#servlet-authorization[authorization] works at the request level in Servlet-based applications. + +.Authorize HttpServletRequest +image::{figures}/authorizationfilter.png[] + +* image:{icondir}/number_1.png[] First, the `AuthorizationFilter` constructs a `Supplier` that retrieves an xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[Authentication] from the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder]. +* image:{icondir}/number_2.png[] Second, it passes the `Supplier` and the `HttpServletRequest` to the xref:servlet/architecture.adoc#authz-authorization-manager[`AuthorizationManager`]. +The `AuthorizationManager` matches the request to the patterns in `authorizeHttpRequests`, and runs the corresponding rule. +** image:{icondir}/number_3.png[] If authorization is denied, xref:servlet/authorization/events.adoc[an `AuthorizationDeniedEvent` is published], and an `AccessDeniedException` is thrown. +In this case the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] handles the `AccessDeniedException`. +** image:{icondir}/number_4.png[] If access is granted, xref:servlet/authorization/events.adoc[an `AuthorizationGrantedEvent` is published] and `AuthorizationFilter` continues with the xref:servlet/architecture.adoc#servlet-filters-review[FilterChain] which allows the application to process normally. + +=== `AuthorizationFilter` Is Last By Default + +The `AuthorizationFilter` is last in xref:servlet/architecture.adoc#servlet-filterchain-figure[the Spring Security filter chain] by default. +This means that Spring Security's xref:servlet/authentication/index.adoc[authentication filters], xref:servlet/exploits/index.adoc[exploit protections], and other filter integrations do not require authorization. +If you add filters of your own before the `AuthorizationFilter`, they will also not require authorization; otherwise, they will. + +A place where this typically becomes important is when you are adding {spring-framework-reference-url}web.html#spring-web[Spring MVC] endpoints. +Because they are executed by the {spring-framework-reference-url}web.html#mvc-servlet[`DispatcherServlet`] and this comes after the `AuthorizationFilter`, you're endpoints need to be <>. + +=== All Dispatches Are Authorized + +The `AuthorizationFilter` runs not just on every request, but on every dispatch. +This means that the `REQUEST` dispatch needs authorization, but also ``FORWARD``s, ``ERROR``s, and ``INCLUDE``s. + +For example, {spring-framework-reference-url}web.html#spring-web[Spring MVC] can `FORWARD` the request to a view resolver that renders a Thymeleaf template, like so: + +.Sample Forwarding Spring MVC Controller +==== +.Java +[source,java,role="primary"] +---- +@Controller +public class MyController { + @GetMapping("/endpoint") + public String endpoint() { + return "endpoint"; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +class MyController { + @GetMapping("/endpoint") + fun endpoint(): String { + return "endpoint" + } +} +---- +==== + +In this case, authorization happens twice; once for authorizing `/endpoint` and once for forwarding to Thymeleaf to render the "endpoint" template. + +For that reason, you may want to <>. + +Another example of this principle is {spring-boot-reference-url}web.html#web.servlet.spring-mvc.error-handling[how Spring Boot handles errors]. +If the container catches an exception, say like the following: + +.Sample Erroring Spring MVC Controller +==== +.Java +[source,java,role="primary"] +---- +@Controller +public class MyController { + @GetMapping("/endpoint") + public String endpoint() { + throw new UnsupportedOperationException("unsupported"); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +class MyController { + @GetMapping("/endpoint") + fun endpoint(): String { + throw UnsupportedOperationException("unsupported") + } +} +---- +==== + +then Boot will dispatch it to the `ERROR` dispatch. + +In that case, authorization also happens twice; once for authorizing `/endpoint` and once for dispatching the error. + +For that reason, you may want to <>. + +=== `Authentication` Lookup is Deferred + +Remember that xref:servlet/authorization/architecture.adoc#_the_authorizationmanager[the `AuthorizationManager` API uses a `Supplier`]. + +This matters with `authorizeHttpRequests` when requests are <>. +In those cases, xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[the `Authentication`] is not queried, making for a faster request. + +[[authorizing-endpoints]] +== Authorizing an Endpoint + +You can configure Spring Security to have different rules by adding more rules in order of precedence. + +If you want to require that `/endpoint` only be accessible by end users with the `USER` authority, then you can do: + +.Authorize an Endpoint +==== +.Java +[source,java,role="primary"] +---- +@Bean +SecurityFilterChain web(HttpSecurity http) throws Exception { + http + .authorizeHttpRequests((authorize) -> authorize + .requestMatchers("/endpoint").hasAuthority('USER') + .anyRequest().authenticated() + ) + // ... + + return http.build(); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Bean +SecurityFilterChain web(HttpSecurity http) throws Exception { + http { + authorizeHttpRequests { + authorize("/endpoint", hasAuthority('USER')) + authorize(anyRequest, authenticated) + } + } + return http.build(); +} +---- + +.Xml +[source,xml,role="secondary"] +---- + + + + +---- +==== + +As you can see, the declaration can be broken up in to pattern/rule pairs. + +`AuthorizationFilter` processes these pairs in the order listed, applying only the first match to the request. +This means that even though `/**` would also match for `/endpoint` the above rules are not a problem. +The way to read the above rules is "if the request is `/endpoint`, then require the `USER` authority; else, only require authentication". + +Spring Security supports several patterns and several rules; you can also programmatically create your own of each. + +Once authorized, you can test it using xref:servlet/test/method.adoc#test-method-withmockuser[Security's test support] in the following way: + +.Test Endpoint Authorization +==== +.Java +[source,java,role="primary"] +---- +@WithMockUser(authorities="USER") +@Test +void endpointWhenUserAuthorityThenAuthorized() { + this.mvc.perform(get("/endpoint")) + .andExpect(status().isOk()); +} + +@WithMockUser +@Test +void endpointWhenNotUserAuthorityThenForbidden() { + this.mvc.perform(get("/endpoint")) + .andExpect(status().isForbidden()); +} + +@Test +void anyWhenUnauthenticatedThenUnauthorized() { + this.mvc.perform(get("/any")) + .andExpect(status().isUnauthorized()) +} +---- +==== + +[[match-requests]] +== Matching Requests + +Above you've already seen <>. + +The first you saw was the simplest, which is to match any request. + +The second is to match by a URI pattern. +Spring Security supports two languages for URI pattern-matching: <> (as seen above) and <>. + +[[match-by-ant]] +=== Matching Using Ant +Ant is the default language that Spring Security uses to match requests. + +You can use it to match a single endpoint or a directory, and you can even capture placeholders for later use. +You can also refine it to match a specific set of HTTP methods. + +Let's say that you instead of wanting to match the `/endpoint` endpoint, you want to match all endpoints under the `/resource` directory. +In that case, you can do something like the following: + +.Match with Ant +==== +.Java +[source,java,role="primary"] +---- +http + .authorizeHttpRequests((authorize) -> authorize + .requestMatchers("/resource/**").hasAuthority("USER") + .anyRequest().authenticated() + ) +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +http { + authorizeHttpRequests { + authorize("/resource/**", hasAuthority("USER")) + authorize(anyRequest, authenticated) + } +} +---- + +.Xml +[source,xml,role="secondary"] +---- + + + + +---- +==== + +The way to read this is "if the request is `/resource` or some subdirectory, require the `USER` authority; otherwise, only require authentication" + +You can also extract path values from the request, as seen below: + +.Authorize and Extract +==== +.Java +[source,java,role="primary"] +---- +http + .authorizeHttpRequests((authorize) -> authorize + .requestMatchers("/resource/{name}").access(new WebExpressionAuthorizationManager("#name == authentication.name")) + .anyRequest().authenticated() + ) +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +http { + authorizeHttpRequests { + authorize("/resource/{name}", WebExpressionAuthorizationManager("#name == authentication.name")) + authorize(anyRequest, authenticated) + } +} +---- + +.Xml +[source,xml,role="secondary"] +---- + + + + +---- +==== + +Once authorized, you can test it using xref:servlet/test/method.adoc#test-method-withmockuser[Security's test support] in the following way: + +.Test Directory Authorization +==== +.Java +[source,java,role="primary"] +---- +@WithMockUser(authorities="USER") +@Test +void endpointWhenUserAuthorityThenAuthorized() { + this.mvc.perform(get("/endpoint/jon")) + .andExpect(status().isOk()); +} + +@WithMockUser +@Test +void endpointWhenNotUserAuthorityThenForbidden() { + this.mvc.perform(get("/endpoint/jon")) + .andExpect(status().isForbidden()); +} + +@Test +void anyWhenUnauthenticatedThenUnauthorized() { + this.mvc.perform(get("/any")) + .andExpect(status().isUnauthorized()) +} +---- +==== + +[NOTE] +Spring Security only matches paths. +If you want to match query parameters, you will need a custom request matcher. + +[[match-by-regex]] +=== Matching Using Regular Expressions +Spring Security supports matching requests against a regular expression. +This can come in handy if you want to apply more strict matching criteria than `**` on a subdirectory. + +For example, consider a path that contains the username and the rule that all usernames must be alphanumeric. +You can use {security-api-url}org/springframework/security/web/util/matcher/RegexRequestMatcher.html[`RegexRequestMatcher`] to respect this rule, like so: + +.Match with Regex +==== +.Java +[source,java,role="primary"] +---- +http + .authorizeHttpRequests((authorize) -> authorize + .requestMatchers(RegexRequestMatcher.regexMatcher("/resource/[A-Za-z0-9]+")).hasAuthority("USER") + .anyRequest().denyAll() + ) +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +http { + authorizeHttpRequests { + authorize(RegexRequestMatcher.regexMatcher("/resource/[A-Za-z0-9]+"), hasAuthority("USER")) + authorize(anyRequest, denyAll) + } +} +---- + +.Xml +[source,xml,role="secondary"] +---- + + + + +---- +==== + +[[match-by-httpmethod]] +=== Matching By Http Method + +You can also match rules by HTTP method. +One place where this is handy is when authorizing by permissions granted, like being granted a `read` or `write` privilege. + +To require all ``GET``s to have the `read` permission and all ``POST``s to have the `write` permission, you can do something like this: + +.Match by HTTP Method +==== +.Java +[source,java,role="primary"] +---- +http + .authorizeHttpRequests((authorize) -> authorize + .requestMatchers(HttpMethod.GET).hasAuthority("read") + .requestMatchers(HttpMethod.POST).hasAuthority("write") + .anyRequest().denyAll() + ) +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +http { + authorizeHttpRequests { + authorize(HttpMethod.GET, hasAuthority("read")) + authorize(HttpMethod.POST, hasAuthority("write")) + authorize(anyRequest, denyAll) + } +} +---- + +.Xml +[source,xml,role="secondary"] +---- + + + + + +---- +==== + +These authorization rules should read as: "if the request is a GET, then require `read` permission; else, if the request is a POST, then require `write` permission; else, deny the request" + +[TIP] +Denying the request by default is a healthy security practice since it turns the set of rules into an allow list. + +Once authorized, you can test it using xref:servlet/test/method.adoc#test-method-withmockuser[Security's test support] in the following way: + +.Test Http Method Authorization +==== +.Java +[source,java,role="primary"] +---- +@WithMockUser(authorities="read") +@Test +void getWhenReadAuthorityThenAuthorized() { + this.mvc.perform(get("/any")) + .andExpect(status().isOk()); +} + +@WithMockUser +@Test +void getWhenNoReadAuthorityThenForbidden() { + this.mvc.perform(get("/any")) + .andExpect(status().isForbidden()); +} + +@WithMockUser(authorities="write") +@Test +void postWhenWriteAuthorityThenAuthorized() { + this.mvc.perform(post("/any").with(csrf())) + .andExpect(status().isOk()) +} + +@WithMockUser(authorities="read") +@Test +void postWhenNoWriteAuthorityThenForbidden() { + this.mvc.perform(get("/any").with(csrf())) + .andExpect(status().isForbidden()); +} +---- +==== + +[[match-by-dispatcher-type]] +=== Matching By Dispatcher Type + +[NOTE] +This feature is not currently supported in XML + +As stated earlier, Spring Security <<_all_dispatches_are_authorized, authorizes all dispatcher types by default>>. +And even though xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontext[the security context] established on the `REQUEST` dispatch carries over to subsequent dispatches, subtle mismatches can sometimes cause an unexpected `AccessDeniedException`. + +To address that, you can configure Spring Security Java configuration to allow dispatcher types like `FORWARD` and `ERROR`, like so: + +.Match by Dispatcher Type +==== +.Java +[source,java,role="secondary"] +---- +http + .authorizeHttpRequests((authorize) -> authorize + .dispatcherTypeMatchers(DispatcherType.FORWARD, DispatcherType.ERROR).permitAll() + .requestMatchers("/endpoint").permitAll() + .anyRequest().denyAll() + ) +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +http { + authorizeHttpRequests { + authorize(DispatcherType.FORWARD, permitAll) + authorize(DispatcherType.ERROR, permitAll) + authorize("/endpoint", permitAll) + authorize(anyRequest, denyAll) + } +} +---- +==== + +[[match-by-custom]] +=== Using a Custom Matcher + +[NOTE] +This feature is not currently supported in XML + +In Java configuration, you can create your own {security-api-url}org/springframework/security/web/util/matcher/RequestMatcher.html[`RequestMatcher`] and supply it to the DSL like so: + +.Authorize by Dispatcher Type +==== +.Java +[source,java,role="secondary"] +---- +RequestMatcher printview = (request) -> request.getParameter("print") != null; +http + .authorizeHttpRequests((authorize) -> authorize + .requestMatchers(printview).hasAuthority("print") + .anyRequest().authenticated() + ) +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +val printview: RequestMatcher = { (request) -> request.getParameter("print") != null } +http { + authorizeHttpRequests { + authorize(printview, hasAuthority("print")) + authorize(anyRequest, authenticated) + } +} +---- +==== + +[TIP] +Because {security-api-url}org/springframework/security/web/util/matcher/RequestMatcher.html[`RequestMatcher`] is a functional interface, you can supply it as a lambda in the DSL. +However, if you want to extract values from the request, you will need to have a concrete class since that requires overriding a `default` method. + +Once authorized, you can test it using xref:servlet/test/method.adoc#test-method-withmockuser[Security's test support] in the following way: + +.Test Custom Authorization +==== +.Java +[source,java,role="primary"] +---- +@WithMockUser(authorities="print") +@Test +void printWhenPrintAuthorityThenAuthorized() { + this.mvc.perform(get("/any?print")) + .andExpect(status().isOk()); +} + +@WithMockUser +@Test +void printWhenNoPrintAuthorityThenForbidden() { + this.mvc.perform(get("/any?print")) + .andExpect(status().isForbidden()); +} +---- +==== + +[[authorize-requests]] +== Authorizing Requests + +Once a request is matched, you can authorize it in several ways <> like `permitAll`, `denyAll`, and `hasAuthority`. + +As a quick summary, here are the authorization rules built into the DSL: + +* `permitAll` - The request requires no authorization and is a public endpoint; note that in this case, xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[the `Authentication`] is never retrieved from the session +* `denyAll` - The request is not allowed under any circumstances; note that in this case, the `Authentication` is never retrieved from the session +* `hasAuthority` - The request requires that the `Authentication` have xref:servlet/authorization/architecture.adoc#authz-authorities[a `GrantedAuthority`] that matches the given value +* `hasRole` - A shortcut for `hasAuthority` that prefixes `ROLE_` or whatever is configured as the default prefix +* `hasAnyAuthority` - The request requires that the `Authentication` have a `GrantedAuthority` that matches any of the given values +* `hasAnyRole` - A shortcut for `hasAnyAuthority` that prefixes `ROLE_` or whatever is configured as the default prefix +* `access` - The request uses this custom `AuthorizationManager` to determine access + +Having now learned the patterns, rules, and how they can be paired together, you should be able to understand what is going on in this more complex example: + +.Authorize Requests +==== +.Java +[source,java,role="primary"] +---- +import static jakarta.servlet.DispatcherType.*; + +import static org.springframework.security.authorization.AuthorizationManagers.allOf; +import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasAuthority; +import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasRole; + +@Bean +SecurityFilterChain web(HttpSecurity http) throws Exception { + http + // ... + .authorizeHttpRequests(authorize -> authorize // <1> + .dispatcherTypeMatchers(FORWARD, ERROR).permitAll() // <2> + .requestMatchers("/static/**", "/signup", "/about").permitAll() // <3> + .requestMatchers("/admin/**").hasRole("ADMIN") // <4> + .requestMatchers("/db/**").access(allOf(hasAuthority('db'), hasRole('ADMIN'))) // <5> + .anyRequest().denyAll() // <6> + ); + + return http.build(); +} +---- +==== +<1> There are multiple authorization rules specified. +Each rule is considered in the order they were declared. +<2> Dispatches `FORWARD` and `ERROR` are permitted to allow {spring-framework-reference-url}web.html#spring-web[Spring MVC] to render views and Spring Boot to render errors +<3> We specified multiple URL patterns that any user can access. +Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about". +<4> Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN". +You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE_" prefix. +<5> Any URL that starts with "/db/" requires the user to have both been granted the "db" permission as well as be a "ROLE_ADMIN". +You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE_" prefix. +<6> Any URL that has not already been matched on is denied access. +This is a good strategy if you do not want to accidentally forget to update your authorization rules. + +[[remote-authorization-manager]] +=== Use an Authorization Database, Policy Agent, or Other Service +If you want to configure Spring Security to use a separate service for authorization, you can create your own `AuthorizationManager` and match it to `anyRequest`. + +First, your `AuthorizationManager` may look something like this: + +.Open Policy Agent Authorization Manager +==== +.Java +[source,java,role="primary"] +---- +@Component +public final class OpenPolicyAgentAuthorizationManager implements AuthorizationManager { + @Override + public AuthorizationDecision check(Supplier authentication, RequestAuthorizationContext context) { + // make request to Open Policy Agent + } +} +---- +==== + +Then, you can wire it into Spring Security in the following way: + +.Any Request Goes to Remote Service +==== +.Java +[source,java,role="primary"] +---- +@Bean +SecurityFilterChain web(HttpSecurity http, AuthorizationManager authz) throws Exception { + http + // ... + .authorizeHttpRequests((authorize) -> authorize + .anyRequest().access(authz) + ); + + return http.build(); +} +---- +==== + +[[favor-permitall]] +=== Favor `permitAll` over `ignoring` +When you have static resources it can be tempting to configure the filter chain to ignore these values. +A more secure approach is to permit them using `permitAll` like so: + +.Permit Static Resources +==== +.Java +[source,java,role="secondary"] +---- +http + .authorizeHttpRequests((authorize) -> authorize + .requestMatchers("/css/**").permitAll() + .anyRequest().authenticated() + ) +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +http { + authorizeHttpRequests { + authorize("/css/**", permitAll) + authorize(anyRequest, authenticated) + } +} +---- +==== + +It's more secure because even with static resources it's important to write secure headers, which Spring Security cannot do if the request is ignored. + +In this past, this came with a performance tradeoff since the session was consulted by Spring Security on every request. +As of Spring Security 6, however, the session is no longer pinged unless required by the authorization rule. +Because the performance impact is now addressed, Spring Security recommends using at least `permitAll` for all requests. + +[[migrate-authorize-requests]] +== Migrating from `authorizeRequests` + +[NOTE] +`AuthorizationFilter` supersedes {security-api-url}org/springframework/security/web/access/intercept/FilterSecurityInterceptor.html[`FilterSecurityInterceptor`]. To remain backward compatible, `FilterSecurityInterceptor` remains the default. This section discusses how `AuthorizationFilter` works and how to override the default configuration. @@ -13,7 +739,7 @@ The {security-api-url}org/springframework/security/web/access/intercept/Authoriz It is inserted into the xref:servlet/architecture.adoc#servlet-filterchainproxy[FilterChainProxy] as one of the xref:servlet/architecture.adoc#servlet-security-filters[Security Filters]. You can override the default when you declare a `SecurityFilterChain`. -Instead of using xref:servlet/authorization/authorize-http-requests.adoc#servlet-authorize-requests-defaults[`authorizeRequests`], use `authorizeHttpRequests`, like so: +Instead of using {security-api-url}org/springframework/security/config/annotation/web/builders/HttpSecurity.html#authorizeRequests()[`authorizeRequests`], use `authorizeHttpRequests`, like so: .Use authorizeHttpRequests ==== @@ -41,247 +767,56 @@ This simplifies reuse and customization. Instead of the authentication needing to be looked up for every request, it will only look it up in requests where an authorization decision requires authentication. 3. Bean-based configuration support. -When `authorizeHttpRequests` is used instead of `authorizeRequests`, then {security-api-url}org/springframework/security/web/access/intercept/AuthorizationFilter.html[`AuthorizationFilter`] is used instead of xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`]. +When `authorizeHttpRequests` is used instead of `authorizeRequests`, then {security-api-url}org/springframework/security/web/access/intercept/AuthorizationFilter.html[`AuthorizationFilter`] is used instead of {security-api-url}org/springframework/security/web/access/intercept/FilterSecurityInterceptor.html[`FilterSecurityInterceptor`]. -.Authorize HttpServletRequest -image::{figures}/authorizationfilter.png[] +=== Migrating Expressions -* image:{icondir}/number_1.png[] First, the `AuthorizationFilter` obtains an xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[Authentication] from the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder]. -It wraps this in an `Supplier` in order to delay lookup. -* image:{icondir}/number_2.png[] Second, it passes the `Supplier` and the `HttpServletRequest` to the xref:servlet/architecture.adoc#authz-authorization-manager[`AuthorizationManager`]. -** image:{icondir}/number_3.png[] If authorization is denied, an `AccessDeniedException` is thrown. -In this case the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] handles the `AccessDeniedException`. -** image:{icondir}/number_4.png[] If access is granted, `AuthorizationFilter` continues with the xref:servlet/architecture.adoc#servlet-filters-review[FilterChain] which allows the application to process normally. +Where possible, it is recommended that you use type-safe authorization managers instead of SpEL. +For Java configuration, {security-api-url}org/springframework/security/web/access/expression/WebExpressionAuthorizationManager.html[`WebExpressionAuthorizationManager`] is available to help migrate legacy SpEL. -We can configure Spring Security to have different rules by adding more rules in order of precedence. +To use `WebExpressionAuthorizationManager`, you can construct one with the expression you are trying to migrate, like so: -.Authorize Requests ==== .Java [source,java,role="primary"] ---- -@Bean -SecurityFilterChain web(HttpSecurity http) throws Exception { - http - // ... - .authorizeHttpRequests(authorize -> authorize // <1> - .requestMatchers("/resources/**", "/signup", "/about").permitAll() // <2> - .requestMatchers("/admin/**").hasRole("ADMIN") // <3> - .requestMatchers("/db/**").access(new WebExpressionAuthorizationManager("hasRole('ADMIN') and hasRole('DBA')")) // <4> - // .requestMatchers("/db/**").access(AuthorizationManagers.allOf(AuthorityAuthorizationManager.hasRole("ADMIN"), AuthorityAuthorizationManager.hasRole("DBA"))) // <5> - .anyRequest().denyAll() // <6> - ); - - return http.build(); -} +.requestMatchers("/test/**").access(new WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')")) ---- -==== -<1> There are multiple authorization rules specified. -Each rule is considered in the order they were declared. -<2> We specified multiple URL patterns that any user can access. -Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about". -<3> Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN". -You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE_" prefix. -<4> Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA". -You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE_" prefix. -<5> The same rule from 4, could be written by combining multiple `AuthorizationManager`. -<6> Any URL that has not already been matched on is denied access. -This is a good strategy if you do not want to accidentally forget to update your authorization rules. -You can take a bean-based approach by constructing your own xref:servlet/authorization/architecture.adoc#authz-delegate-authorization-manager[`RequestMatcherDelegatingAuthorizationManager`] like so: - -.Configure RequestMatcherDelegatingAuthorizationManager -==== -.Java -[source,java,role="primary"] ----- -@Bean -SecurityFilterChain web(HttpSecurity http, AuthorizationManager access) - throws AuthenticationException { - http - .authorizeHttpRequests((authorize) -> authorize - .anyRequest().access(access) - ) - // ... - - return http.build(); -} - -@Bean -AuthorizationManager requestMatcherAuthorizationManager(HandlerMappingIntrospector introspector) { - MvcRequestMatcher.Builder mvcMatcherBuilder = new MvcRequestMatcher.Builder(introspector); - RequestMatcher permitAll = - new AndRequestMatcher( - mvcMatcherBuilder.pattern("/resources/**"), - mvcMatcherBuilder.pattern("/signup"), - mvcMatcherBuilder.pattern("/about")); - RequestMatcher admin = mvcMatcherBuilder.pattern("/admin/**"); - RequestMatcher db = mvcMatcherBuilder.pattern("/db/**"); - RequestMatcher any = AnyRequestMatcher.INSTANCE; - AuthorizationManager manager = RequestMatcherDelegatingAuthorizationManager.builder() - .add(permitAll, (context) -> new AuthorizationDecision(true)) - .add(admin, AuthorityAuthorizationManager.hasRole("ADMIN")) - .add(db, AuthorityAuthorizationManager.hasRole("DBA")) - .add(any, new AuthenticatedAuthorizationManager()) - .build(); - return (context) -> manager.check(context.getRequest()); -} ----- -==== - -You can also wire xref:servlet/authorization/architecture.adoc#authz-custom-authorization-manager[your own custom authorization managers] for any request matcher. - -Here is an example of mapping a custom authorization manager to the `my/authorized/endpoint`: - -.Custom Authorization Manager -==== -.Java -[source,java,role="primary"] ----- -@Bean -SecurityFilterChain web(HttpSecurity http) throws Exception { - http - .authorizeHttpRequests((authorize) -> authorize - .requestMatchers("/my/authorized/endpoint").access(new CustomAuthorizationManager()); - ) - // ... - - return http.build(); -} ----- -==== - -Or you can provide it for all requests as seen below: - -.Custom Authorization Manager for All Requests -==== -.Java -[source,java,role="primary"] ----- -@Bean -SecurityFilterChain web(HttpSecurity http) throws Exception { - http - .authorizeHttpRequests((authorize) -> authorize - .anyRequest().access(new CustomAuthorizationManager()); - ) - // ... - - return http.build(); -} ----- -==== - -By default, the `AuthorizationFilter` applies to all dispatcher types. -We can configure Spring Security to not apply the authorization rules to all dispatcher types by using the `shouldFilterAllDispatcherTypes` method: - -.Set shouldFilterAllDispatcherTypes to false -==== -.Java -[source,java,role="primary"] ----- -@Bean -SecurityFilterChain web(HttpSecurity http) throws Exception { - http - .authorizeHttpRequests((authorize) -> authorize - .shouldFilterAllDispatcherTypes(false) - .anyRequest().authenticated() - ) - // ... - - return http.build(); -} ----- .Kotlin [source,kotlin,role="secondary"] ---- -@Bean -open fun web(http: HttpSecurity): SecurityFilterChain { - http { - authorizeHttpRequests { - shouldFilterAllDispatcherTypes = false - authorize(anyRequest, authenticated) - } - } - return http.build() -} +.requestMatchers("/test/**").access(WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')")) ---- ==== -Instead of setting `shouldFilterAllDispatcherTypes` to `false`, the recommended approach is to customize authorization on the dispatcher types. -For example, you may want to grant all access on requests with dispatcher type `ASYNC` or `FORWARD`. +If you are referring to a bean in your expression like so: `@webSecurity.check(authentication, request)`, it's recommended that you instead call the bean directly, which will look something like the following: -.Permit ASYNC and FORWARD dispatcher type ==== .Java [source,java,role="primary"] ---- -@Bean -SecurityFilterChain web(HttpSecurity http) throws Exception { - http - .authorizeHttpRequests((authorize) -> authorize - .dispatcherTypeMatchers(DispatcherType.ASYNC, DispatcherType.FORWARD).permitAll() - .anyRequest().authenticated() - ) - // ... - - return http.build(); -} +.requestMatchers("/test/**").access((authentication, context) -> + new AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest()))) ---- + .Kotlin [source,kotlin,role="secondary"] ---- -@Bean -open fun web(http: HttpSecurity): SecurityFilterChain { - http { - authorizeHttpRequests { - authorize(DispatcherTypeRequestMatcher(DispatcherType.ASYNC, DispatcherType.FORWARD), permitAll) - authorize(anyRequest, authenticated) - } - } - return http.build() -} +.requestMatchers("/test/**").access((authentication, context): AuthorizationManager -> + AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest()))) ---- ==== -You can also customize it to require a specific role for a dispatcher type: +For complex instructions that include bean references as well as other expressions, it is recommended that you change those to implement `AuthorizationManager` and refer to them by calling `.access(AuthorizationManager)`. -.Require ADMIN for Dispatcher Type ERROR -==== -.Java -[source,java,role="primary"] ----- -@Bean -SecurityFilterChain web(HttpSecurity http) throws Exception { - http - .authorizeHttpRequests((authorize) -> authorize - .dispatcherTypeMatchers(DispatcherType.ERROR).hasRole("ADMIN") - .anyRequest().authenticated() - ) - // ... +If you are not able to do that, you can configure a {security-api-url}org/springframework/security/web/access/expression/DefaultHttpSecurityExpressionHandler.html[`DefaultHttpSecurityExpressionHandler`] with a bean resolver and supply that to `WebExpressionAuthorizationManager#setExpressionhandler`. - return http.build(); -} ----- -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -open fun web(http: HttpSecurity): SecurityFilterChain { - http { - authorizeHttpRequests { - authorize(DispatcherTypeRequestMatcher(DispatcherType.ERROR), hasRole("ADMIN")) - authorize(anyRequest, authenticated) - } - } - return http.build() -} ----- -==== +[[security-matchers]] +== Security Matchers -== Request Matchers - -The `RequestMatcher` interface is used to determine if a request matches a given rule. -We use `securityMatchers` to determine if a given `HttpSecurity` should be applied to a given request. +The {security-api-url}org/springframework/security/web/util/matcher/RequestMatcher.html[`RequestMatcher`] interface is used to determine if a request matches a given rule. +We use `securityMatchers` to determine if xref:servlet/configuration/java.adoc#jc-httpsecurity[a given `HttpSecurity`] should be applied to a given request. The same way, we can use `requestMatchers` to determine the authorization rules that we should apply to a given request. Look at the following example: @@ -336,7 +871,7 @@ open class SecurityConfig { <3> Allow access to URLs that start with `/admin/` to users with the `ADMIN` role <4> Any other request that doesn't match the rules above, will require authentication -The `securityMatcher(s)` and `requestMatcher(s)` methods will decide which `RequestMatcher` implementation fits best for your application: If Spring MVC is in the classpath, then `MvcRequestMatcher` will be used, otherwise, `AntPathRequestMatcher` will be used. +The `securityMatcher(s)` and `requestMatcher(s)` methods will decide which `RequestMatcher` implementation fits best for your application: If {spring-framework-reference-url}web.html#spring-web[Spring MVC] is in the classpath, then {security-api-url}org/springframework/security/web/servlet/util/matcher/MvcRequestMatcher.html[`MvcRequestMatcher`] will be used, otherwise, {security-api-url}org/springframework/security/web/servlet/util/matcher/AntPathRequestMatcher.html[`AntPathRequestMatcher`] will be used. You can read more about the Spring MVC integration xref:servlet/integrations/mvc.adoc[here]. If you want to use a specific `RequestMatcher`, just pass an implementation to the `securityMatcher` and/or `requestMatcher` methods: @@ -409,45 +944,7 @@ open class SecurityConfig { <4> Allow access to URLs that start with `/admin/` to users with the `ADMIN` role, using `RegexRequestMatcher` <5> Allow access to URLs that match the `MyCustomRequestMatcher` to users with the `SUPERVISOR` role, using a custom `RequestMatcher` -== Expressions +== Further Reading -It is recommended that you use type-safe authorization managers instead of SpEL. -However, `WebExpressionAuthorizationManager` is available to help migrate legacy SpEL. - -To use `WebExpressionAuthorizationManager`, you can construct one with the expression you are trying to migrate, like so: - -==== -.Java -[source,java,role="primary"] ----- -.requestMatchers("/test/**").access(new WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')")) ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -.requestMatchers("/test/**").access(WebExpressionAuthorizationManager("hasRole('ADMIN') && hasRole('USER')")) ----- -==== - -If you are referring to a bean in your expression like so: `@webSecurity.check(authentication, request)`, it's recommended that you instead call the bean directly, which will look something like the following: - -==== -.Java -[source,java,role="primary"] ----- -.requestMatchers("/test/**").access((authentication, context) -> - new AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest()))) ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -.requestMatchers("/test/**").access((authentication, context): AuthorizationManager -> - AuthorizationDecision(webSecurity.check(authentication.get(), context.getRequest()))) ----- -==== - -For complex instructions that include bean references as well as other expressions, it is recommended that you change those to implement `AuthorizationManager` and refer to them by calling `.access(AuthorizationManager)`. - -If you are not able to do that, you can configure a `DefaultHttpSecurityExpressionHandler` with a bean resolver and supply that to `WebExpressionAuthorizationManager#setExpressionhandler`. +Now that you have secured your application's requests, consider xref:servlet/authorization/method-security.adoc[securing its methods]. +You can also read further on xref:servlet/test/index.adoc[testing your application] or on integrating Spring Security with other aspects of you application like xref:servlet/integrations/data.adoc[the data layer] or xref:servlet/integrations/observability.adoc[tracing and metrics]. diff --git a/docs/modules/ROOT/pages/servlet/authorization/authorize-requests.adoc b/docs/modules/ROOT/pages/servlet/authorization/authorize-requests.adoc deleted file mode 100644 index 83d62c42da..0000000000 --- a/docs/modules/ROOT/pages/servlet/authorization/authorize-requests.adoc +++ /dev/null @@ -1,183 +0,0 @@ -[[servlet-authorization-filtersecurityinterceptor]] -= Authorize HttpServletRequest with FilterSecurityInterceptor -:figures: servlet/authorization - -[NOTE] -==== -`FilterSecurityInterceptor` is in the process of being replaced by xref:servlet/authorization/authorize-http-requests.adoc[`AuthorizationFilter`]. -Consider using that instead. -==== - -This section builds on xref:servlet/architecture.adoc#servlet-architecture[Servlet Architecture and Implementation] by digging deeper into how xref:servlet/authorization/index.adoc#servlet-authorization[authorization] works within Servlet-based applications. - -The {security-api-url}org/springframework/security/web/access/intercept/FilterSecurityInterceptor.html[`FilterSecurityInterceptor`] provides xref:servlet/authorization/index.adoc#servlet-authorization[authorization] for `HttpServletRequest` instances. -It is inserted into the xref:servlet/architecture.adoc#servlet-filterchainproxy[FilterChainProxy] as one of the xref:servlet/architecture.adoc#servlet-security-filters[Security Filters]. - -The following image shows the role of `FilterSecurityInterceptor`: - -.Authorize HttpServletRequest -image::{figures}/filtersecurityinterceptor.png[] - -image:{icondir}/number_1.png[] The `FilterSecurityInterceptor` obtains an xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[Authentication] from the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder]. -image:{icondir}/number_2.png[] `FilterSecurityInterceptor` creates a {security-api-url}org/springframework/security/web/FilterInvocation.html[`FilterInvocation`] from the `HttpServletRequest`, `HttpServletResponse`, and `FilterChain` that are passed into the `FilterSecurityInterceptor`. -image:{icondir}/number_3.png[] It passes the `FilterInvocation` to `SecurityMetadataSource` to get the ``ConfigAttribute``s. -image:{icondir}/number_4.png[] It passes the `Authentication`, `FilterInvocation`, and ``ConfigAttribute``s to the `AccessDecisionManager`. -image:{icondir}/number_5.png[] If authorization is denied, an `AccessDeniedException` is thrown. -In this case, the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] handles the `AccessDeniedException`. -image:{icondir}/number_6.png[] If access is granted, `FilterSecurityInterceptor` continues with the xref:servlet/architecture.adoc#servlet-filters-review[`FilterChain`], which lets the application process normally. - -// configuration (xml/java) - -By default, Spring Security's authorization requires all requests to be authenticated. -The following listing shows the explicit configuration: - -[[servlet-authorize-requests-defaults]] -.Every Request Must be Authenticated -==== -.Java -[source,java,role="primary"] ----- -@Bean -public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http - // ... - .authorizeRequests(authorize -> authorize - .anyRequest().authenticated() - ); - return http.build(); -} ----- - -.XML -[source,xml,role="secondary"] ----- - - - - ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -open fun filterChain(http: HttpSecurity): SecurityFilterChain { - http { - // ... - authorizeRequests { - authorize(anyRequest, authenticated) - } - } - return http.build() -} ----- -==== - -We can configure Spring Security to have different rules by adding more rules in order of precedence: - -.Authorize Requests -==== -.Java -[source,java,role="primary"] ----- -@Bean -public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { - http - // ... - .authorizeRequests(authorize -> authorize // <1> - .requestMatchers("/resources/**", "/signup", "/about").permitAll() // <2> - .requestMatchers("/admin/**").hasRole("ADMIN") // <3> - .requestMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") // <4> - .anyRequest().denyAll() // <5> - ); - return http.build(); -} ----- - -.XML -[source,xml,role="secondary"] ----- - - - - - - - - - - - ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Bean -open fun filterChain(http: HttpSecurity): SecurityFilterChain { - http { - authorizeRequests { // <1> - authorize("/resources/**", permitAll) // <2> - authorize("/signup", permitAll) - authorize("/about", permitAll) - - authorize("/admin/**", hasRole("ADMIN")) // <3> - authorize("/db/**", "hasRole('ADMIN') and hasRole('DBA')") // <4> - authorize(anyRequest, denyAll) // <5> - } - } - return http.build() -} ----- -==== -<1> There are multiple authorization rules specified. -Each rule is considered in the order they were declared. -<2> We specified multiple URL patterns that any user can access. -Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about". -<3> Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN". -You will notice that since we are invoking the `hasRole` method we do not need to specify the "ROLE_" prefix. -<4> Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA". -You will notice that since we are using the `hasRole` expression we do not need to specify the "ROLE_" prefix. -<5> Any URL that has not already been matched on is denied access. -This is a good strategy if you do not want to accidentally forget to update your authorization rules. -==== - - -[[filtersecurityinterceptor-every-request]] -== Configure FilterSecurityInterceptor with Dispatcher Types - -By default, the `FilterSecurityInterceptor` applies to every request. -This means that if a request is dispatched from a request that was already filtered, the `FilterSecurityInterceptor` will perform the same authorization checks on the dispatched request. -In some scenarios, you may not want to apply authorization on some dispatcher types: - -.Permit ASYNC and ERROR dispatcher types -==== -.Java -[source,java,role="primary"] ----- -@Bean -SecurityFilterChain web(HttpSecurity http) throws Exception { - http - .authorizeRequests((authorize) -> authorize - .dispatcherTypeMatchers(DispatcherType.ASYNC, DispatcherType.ERROR).permitAll() - .anyRequest.authenticated() - ) - // ... - - return http.build(); -} ----- -.XML -[source,xml] ----- - - - - - - - - - ----- -==== diff --git a/docs/modules/ROOT/pages/servlet/authorization/index.adoc b/docs/modules/ROOT/pages/servlet/authorization/index.adoc index a528115372..1a0579336b 100644 --- a/docs/modules/ROOT/pages/servlet/authorization/index.adoc +++ b/docs/modules/ROOT/pages/servlet/authorization/index.adoc @@ -2,11 +2,12 @@ = Authorization :page-section-summary-toc: 1 +Having established xref:servlet/authentication/index.adoc[how users will authenticate], you also need to configure your application's authorization rules. + The advanced authorization capabilities within Spring Security represent one of the most compelling reasons for its popularity. Irrespective of how you choose to authenticate (whether using a Spring Security-provided mechanism and provider or integrating with a container or other non-Spring Security authentication authority), the authorization services can be used within your application in a consistent and simple way. -In this part, we explore the different `AbstractSecurityInterceptor` implementations, which were introduced in Part I. -We then move on to explore how to fine-tune authorization through the use of domain access control lists. - +You should consider attaching authorization rules to xref:servlet/authorization/authorize-http-requests.adoc[request URIs] and xref:servlet/authorization/method-security.adoc[methods] to begin. +Below there is also wealth of detail about xref:servlet/authorization/architecture.adoc[how Spring Security authorization works] and how, having established a basic model, it can be fine-tuned. diff --git a/docs/modules/ROOT/pages/servlet/authorization/method-security.adoc b/docs/modules/ROOT/pages/servlet/authorization/method-security.adoc index 60da21403f..0d29172b50 100644 --- a/docs/modules/ROOT/pages/servlet/authorization/method-security.adoc +++ b/docs/modules/ROOT/pages/servlet/authorization/method-security.adoc @@ -1,54 +1,24 @@ [[jc-method]] = Method Security +:figures: servlet/authorization -From version 2.0 onwards, Spring Security has improved support substantially for adding security to your service layer methods. -It provides support for JSR-250 annotation security as well as the framework's original `@Secured` annotation. -From 3.0, you can also make use of new xref:servlet/authorization/expression-based.adoc#el-access[expression-based annotations]. -You can apply security to a single bean, by using the `intercept-methods` element to decorate the bean declaration, or you can secure multiple beans across the entire service layer by using AspectJ style pointcuts. +In addition to xref:servlet/authorization/authorize-http-requests.adoc[modeling authorization at the request level], Spring Security also supports modeling at the method level. -[[jc-enable-method-security]] -== EnableMethodSecurity +[[activate-method-security]] +You can activate it in your application by annotating any `@Configuration` class with `@EnableMethodSecurity` or adding `` to any XML configuration file, like so: -In Spring Security 5.6, we can enable annotation-based security using the `@EnableMethodSecurity` annotation on any `@Configuration` instance. - -This improves upon `@EnableGlobalMethodSecurity` in a number of ways. `@EnableMethodSecurity`: - -1. Uses the simplified `AuthorizationManager` API instead of metadata sources, config attributes, decision managers, and voters. -This simplifies reuse and customization. -2. Favors direct bean-based configuration, instead of requiring extending `GlobalMethodSecurityConfiguration` to customize beans -3. Is built using native Spring AOP, removing abstractions and allowing you to use Spring AOP building blocks to customize -4. Checks for conflicting annotations to ensure an unambiguous security configuration -5. Complies with JSR-250 -6. Enables `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter` by default - -[NOTE] -==== -For earlier versions, please read about similar support with <>. -==== - -For example, the following would enable Spring Security's `@PreAuthorize` annotation: - -.Method Security Configuration ==== .Java [source,java,role="primary"] ---- -@Configuration @EnableMethodSecurity -public class MethodSecurityConfig { - // ... -} ---- .Kotlin [source,kotlin,role="secondary"] ---- -@Configuration @EnableMethodSecurity -class MethodSecurityConfig { - // ... -} ---- .Xml @@ -58,66 +28,683 @@ class MethodSecurityConfig { ---- ==== -Adding an annotation to a method (on a class or interface) would then limit the access to that method accordingly. -Spring Security's native annotation support defines a set of attributes for the method. -These will be passed to the `DefaultAuthorizationMethodInterceptorChain` for it to make the actual decision: +Then, you are immediately able to annotate any Spring-managed class or method with <>, <>, <>, and <> to authorize method invocations, including the input parameters and return values. + +[NOTE] +{spring-boot-reference-url}using.html#using.build-systems.starters[Spring Boot Starter Security] does not activate method-level authorization by default. + +Method Security supports many other use cases as well including <>, <>, and several configuration points. +Consider learning about the following use cases: + +* <> +* Understanding <> and reasons to use it +* Comparing <> +* Authorizing methods with <> and <> +* Filtering methods with <> and <> +* Authorizing methods with <> +* Authorizing methods with <> +* Integrating with <> +* Customizing <> +* Integrating with <> + +[[method-security-architecture]] +== How Method Security Works + +Spring Security's method authorization support is handy for: + +* Extracting fine-grained authorization logic; for example, when the method parameters and return values contribute to the authorization decision. +* Enforcing security at the service layer +* Stylistically favoring annotation-based over `HttpSecurity`-based configuration + +And since Method Security is built using {spring-framework-reference-url}core.html#aop-api[Spring AOP], you have access to all its expressive power to override Spring Security's defaults as needed. + +As already mentioned, you begin by adding `@EnableMethodSecurity` to a `@Configuration` class or `` in a Spring XML configuration file. + +[[use-method-security]] +[NOTE] +==== +This annotation and XML element supercede `@EnableGlobalMethodSecurity` and ``, respectively. +They offer the following improvements: + +1. Uses the simplified `AuthorizationManager` API instead of metadata sources, config attributes, decision managers, and voters. +This simplifies reuse and customization. +2. Favors direct bean-based configuration, instead of requiring extending `GlobalMethodSecurityConfiguration` to customize beans +3. Is built using native Spring AOP, removing abstractions and allowing you to use Spring AOP building blocks to customize +4. Checks for conflicting annotations to ensure an unambiguous security configuration +5. Complies with JSR-250 +6. Enables `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter` by default + +If you are using `@EnableGlobalMethodSecurity` or ``, these are now deprecated, and you are encouraged to migrate. +==== + +Method authorization is a combination of before- and after-method authorization. +Consider a service bean that is annotated in the following way: -.Method Security Annotation Usage ==== .Java [source,java,role="primary"] ---- -public interface BankService { - @PreAuthorize("hasRole('USER')") - Account readAccount(Long id); - - @PreAuthorize("hasRole('USER')") - List findAccounts(); - - @PreAuthorize("hasRole('TELLER')") - Account post(Account account, Double amount); +@Service +public class MyCustomerService { + @PreAuthorize("hasAuthority('permission:read')") + @PostAuthorize("returnObject.owner == authentication.name") + public Customer readCustomer(String id) { ... } } ---- .Kotlin [source,kotlin,role="secondary"] ---- -interface BankService { - @PreAuthorize("hasRole('USER')") - fun readAccount(id : Long) : Account - - @PreAuthorize("hasRole('USER')") - fun findAccounts() : List - - @PreAuthorize("hasRole('TELLER')") - fun post(account : Account, amount : Double) : Account +@Service +open class MyCustomerService { + @PreAuthorize("hasAuthority('permission:read')") + @PostAuthorize("returnObject.owner == authentication.name") + fun readCustomer(val id: String): Customer { ... } } ---- ==== -You can enable support for Spring Security's `@Secured` annotation using: +A given invocation to `MyCustomerService#readCustomer` may look something like this when Method Security <>: + +image::{figures}/methodsecurity.png[] + +1. Spring AOP invokes its proxy method for `readCustomer`. Among the proxy's other advisors, it invokes an {security-api-url}org/springframework/security/authorization/method/AuthorizationManagerBeforeMethodInterceptor/html[`AuthorizationManagerBeforeMethodInterceptor`] that matches <> +2. The interceptor invokes {security-api-url}org/springframework/security/authorization/method/PreAuthorizeAuthorizationManager.html[`PreAuthorizeAuthorizationManager#check`] +3. The authorization manager uses a `MethodSecurityExpressionHandler` to parse the annotation's xref:servlet/authorization/expression-based.adoc[SpEL expression] and constructs a corresponding `EvaluationContext` from a `MethodSecurityExpressionRoot` containing xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[a `Supplier`] and `MethodInvocation`. +4. The interceptor uses this context to evaluate the expression; specifically, it reads xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[the `Authentication`] from the `Supplier` and checks whether it has `permission:read` in its collection of xref:servlet/authorization/architecture.adoc#authz-authorities[authorities] +5. If the evaluation passes, then Spring AOP proceeds to invoke the method. +6. If not, the interceptor publishes an `AuthorizationDeniedEvent` and throws an {security-api-url}org/springframework/security/access/AccessDeniedException.html[`AccessDeniedException`] which xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[the `ExceptionTranslationFilter`] catches and returns a 403 status code to the response +7. After the method returns, Spring AOP invokes an {security-api-url}org/springframework/security/authorization/method/AuthorizationManagerAfterMethodInterceptor.html[`AuthorizationManagerAfterMethodInterceptor`] that matches <>, operating the same as above, but with {security-api-url}org/springframework/security/authorization/method/PostAuthorizeAuthorizationManager.html[`PostAuthorizeAuthorizationManager`] +8. If the evaluation passes (in this case, the return value belongs to the logged-in user), processing continues normally +9. If not, the interceptor publishes an `AuthorizationDeniedEvent` and throws an {security-api-url}org/springframework/security/access/AccessDeniedException.html[`AccessDeniedException`], which xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[the `ExceptionTranslationFilter`] catches and returns a 403 status code to the response + +[NOTE] +If the method is not being called in the context of an HTTP request, you will likely need to handle the `AccessDeniedException` yourself + +[[unanimous-based-authorization-decisions]] +=== Multiple Annotations Are Computed In Series + +As demonstrated above, if a method invocation involves multiple <>, each of those is processed one at a time. +This means that they can collectively be thought of as being "anded" together. +In other words, for an invocation to be authorized, all annotation inspections need to pass authorization. + +[[repeated-annotations]] +=== Repeated Annotations Are Not Supported + +That said, it is not supported to repeat the same annotation on the same method. +For example, you cannot please `@PreAuthorize` twice on the same method. + +Instead, use SpEL's boolean support or its support for delegating to a separate bean. + +[[annotation-method-pointcuts]] +=== Each Annotation Has Its Own Pointcut + +Each annotation has its own pointcut instance that looks for that annotation or its <> counterparts across the entire object hierarchy, starting at <>. + +You can see the specifics of this in {security-api-url}org/springframework/security/authorization/method/AuthorizationMethodPointcuts.html[`AuthorizationMethodPointcuts`]. + +[[annotation-method-interceptors]] +=== Each Annotation Has Its Own Method Interceptor + +Each annotation has its own dedicated method interceptor. +The reason for this is to make things more composable. +For example, if needed, you can disable the Spring Security defaults and <<_enabling_certain_annotations,publish only the `@PostAuthorize` method interceptor>>. + +The method interceptors are as follows: + +* For <>, Spring Security uses {security-api-url}org/springframework/security/authorization/method/AuthorizationManagerBeforeMethodInterceptor.html[`AuthenticationManagerBeforeMethodInterceptor#preAuthorize`], which in turn uses {security-api-url}org/springframework/security/authorization/method/PreAuthorizeAuthorizationManager.html[`PreAuthorizeAuthorizationManager`] +* For <>, Spring Security uses {security-api-url}org/springframework/security/authorization/method/AuthorizationManagerAfterMethodInterceptor.html[`AuthenticationManagerAfterMethodInterceptor#postAuthorize`], which in turn uses {security-api-url}org/springframework/security/authorization/method/PostAuthorizeAuthorizationManager.html[`PostAuthorizeAuthorizationManager`] +* For <>, Spring Security uses {security-api-url}org/springframework/security/authorization/method/PreFilterAuthorizationMethodInterceptor.html[`PreFilterAuthorizationMethodInterceptor`] +* For <>, Spring Security uses {security-api-url}org/springframework/security/authorization/method/PostFilterAuthorizationMethodInterceptor.html[`PostFilterAuthorizationMethodInterceptor`] +* For <>, Spring Security uses {security-api-url}org/springframework/security/authorization/method/AuthorizationManagerBeforeMethodInterceptor.html[`AuthenticationManagerBeforeMethodInterceptor#secured`], which in turn uses {security-api-url}org/springframework/security/authorization/method/SecuredAuthorizationManager.html[`SecuredAuthorizationManager`] +* For JSR-250 annotations, Spring Security uses {security-api-url}org/springframework/security/authorization/method/AuthorizationManagerBeforeMethodInterceptor.html[`AuthenticationManagerBeforeMethodInterceptor#jsr250`], which in turn uses {security-api-url}org/springframework/security/authorization/method/Jsr250AuthorizationManager.html[`Jsr250AuthorizationManager`] + +Generally speaking, you can consider the following listing as representative of what interceptors Spring Security publishes when you add `@EnableMethodSecurity`: -.@Secured Configuration ==== .Java [source,java,role="primary"] ---- -@Configuration -@EnableMethodSecurity(securedEnabled = true) -public class MethodSecurityConfig { - // ... +@Bean +@Role(BeanDefinition.ROLE_INFRASTRUCTURE) +static Advisor preAuthorizeMethodInterceptor() { + return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(); +} + +@Bean +@Role(BeanDefinition.ROLE_INFRASTRUCTURE) +static Advisor postAuthorizeMethodInterceptor() { + return AuthorizationManagerAfterMethodInterceptor.postAuthorize(); +} + +@Bean +@Role(BeanDefinition.ROLE_INFRASTRUCTURE) +static Advisor preFilterMethodInterceptor() { + return AuthorizationManagerBeforeMethodInterceptor.preFilter(); +} + +@Bean +@Role(BeanDefinition.ROLE_INFRASTRUCTURE) +static Advisor postFilterMethodInterceptor() { + return AuthorizationManagerAfterMethodInterceptor.postFilter(); +} +---- +==== + +[[favor-granting-authorities]] +=== Favor Granting Authorities Over Complicated SpEL Expressions + +Quite often it can be tempting to introduce a complicated SpEL expression like the following: + +==== +.Java +[source,java,role="primary"] +---- +@PreAuthorize("hasAuthority('permission:read') || hasRole('ADMIN')") +---- + +.Kotlin +[source,kotlin,role="kotlin"] +---- +@PreAuthorize("hasAuthority('permission:read') || hasRole('ADMIN')") +---- +==== + +However, you could instead grant `permission:read` to those with `ROLE_ADMIN`. +One way to do this is with a `RoleHierarchy` like so: + +==== +.Java +[source,java,role="primary"] +---- +@Bean +static RoleHierarchy roleHierarchy() { + return new RoleHierarchyImpl("ROLE_ADMIN > permission:read"); +} +---- + +.Kotlin +[source,java,role="secondary"] +---- +companion object { + @Bean + fun roleHierarchy(): RoleHierarchy { + return RoleHierarchyImpl("ROLE_ADMIN > permission:read") + } +} +---- + +.Xml +[source,xml,role="secondary"] +---- + + + +---- +==== + +and then <>. +This then allows you to have a simpler <> expression like this one: + +==== +.Java +[source,java,role="primary"] +---- +@PreAuthorize("hasAuthority('permission:read')") +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@PreAuthorize("hasAuthority('permission:read')") +---- +==== + +Or, where possible, adapt application-specific authorization logic into granted authorities at login time. + +[[request-vs-method]] +== Comparing Request-level vs Method-level Authorization + +When should you favor method-level authorization over xref:servlet/authorization/authorize-http-requests.adoc[request-level authorization]? +Some of it comes down to taste; however, consider the following strengths list of each to help you decide. + +|=== +|| *request-level* | *method-level* +| *authorization type* | coarse-grained | fine-grained +| *configuration location* | declared in a config class | local to method declaration +| *configuration style* | DSL | Annotations +| *authorization definitions* | programmatic | SpEL +|=== + +The main tradeoff seems to be where you want your authorization rules to live. + +[NOTE] +It's important to remember that when you use annotation-based Method Security, then unannotated methods are not secured. +To protect against this, declare xref:servlet/authorization/authorize-http-requests.adoc#activate-request-security[a catch-all authorization rule] in your xref:servlet/configuration/java.adoc#jc-httpsecurity[`HttpSecurity`] instance. + +[[authorizing-with-annotations]] +== Authorizing with Annotations + +The primary way Spring Security enables method-level authorization support is through annotations that you can add to methods, classes, and interfaces. + +[[use-preauthorize]] +=== Authorizing Method Invocation with `@PreAuthorize` + +When <>, you can annotate a method with the {security-api-url}org/springframework/security/access/prepost/PreAuthorize.html[`@PreAuthorize`] annotation like so: + +==== +.Java +[source,java,role="primary"] +---- +@Component +public class BankService { + @PreAuthorize("hasRole('ADMIN')") + public Account readAccount(Long id) { + // ... is only invoked if the `Authentication` has the `ROLE_ADMIN` authority + } } ---- .Kotlin [source,kotlin,role="secondary"] ---- -@Configuration -@EnableMethodSecurity(securedEnabled = true) -class MethodSecurityConfig { - // ... +@Component +open class BankService { + @PreAuthorize("hasRole('ADMIN')") + fun readAccount(val id: Long): Account { + // ... is only invoked if the `Authentication` has the `ROLE_ADMIN` authority + } } ---- +==== + +This is meant to indicate that the method can only be invoked if the provided expression `hasRole('ADMIN')` passes. + +You can then xref:servlet/test/method.adoc[test the class] to confirm it is enforcing the authorization rule like so: + +==== +.Java +[source,java,role="primary"] +---- +@Autowired +BankService bankService; + +@WithMockUser(roles="ADMIN") +@Test +void readAccountWithAdminRoleThenInvokes() { + Account account = this.bankService.readAccount("12345678"); + // ... assertions +} + +@WithMockUser(roles="WRONG") +@Test +void readAccountWithWrongRoleThenAccessDenied() { + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy( + () -> this.bankService.readAccount("12345678")); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@WithMockUser(roles="ADMIN") +@Test +fun readAccountWithAdminRoleThenInvokes() { + val account: Account = this.bankService.readAccount("12345678") + // ... assertions +} + +@WithMockUser(roles="WRONG") +@Test +fun readAccountWithWrongRoleThenAccessDenied() { + assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy { + this.bankService.readAccount("12345678") + } +} +---- +==== + +[TIP] +`@PreAuthorize` also can be a <>, be defined <>, and use xref:servlet/authorization/expression-based.adoc[SpEL authorization expressions]. + +While `@PreAuthorize` is quite helpful for declaring needed authorities, it can also be used to evaluate more complex permissions that involve the method parameters. +To achieve that, you can use Spring Security's `@P` annotation to remember the parameter name: + +==== +.Java +[source,java,role="primary"] +---- +@PreAuthorize("#username == authentication.name") +Collection findOrders(@P("username") String username) { ... } +---- + +.Kotlin +[source,java,role="secondary"] +---- +@PreAuthorize("#username == authentication.name") +fun findOrders(@P("username") val username: String): Collection { ... } +---- +==== + +Or, Spring Security also integrate with {spring-framework-reference-url}web.html#spring-web[Spring MVC] to identify parameters like so: + +==== +[source,java,role="primary"] +---- +@GetMapping("/orders/{username}") +@PreAuthorize("#username == authentication.name") +Collection findOrders(@PathVariable("username") String username) { ... } +---- + +[source,kotlin,role="secondary"] +---- +@GetMapping("/orders/{username}") +@PreAuthorize("#username == authentication.name") +fun findOrders(@PathVariable("username") val username: String): Collection { ... } +---- +==== + +The above two snippets are ensuring that the user can only request orders that belong to them by comparing the username parameter to xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication#getName`]. + +The result is that the above method will only be invoked if the `username` in the request path matches the logged-in user's `name`. +If not, Spring Security will throw an `AccessDeniedException` and return a 403 status code. + +[[use-postauthorize]] +=== Authorization Method Results with `@PostAuthorize` + +When Method Security is active, you can annotate a method with the {security-api-url}org/springframework/security/access/prepost/PostAuthorize.html[`@PostAuthorize`] annotation like so: + +==== +.Java +[source,java,role="primary"] +---- +@Component +public class BankService { + @PostAuthorize("returnObject.owner == authentication.name") + public Account readAccount(Long id) { + // ... is only returned if the `Account` belongs to the logged in user + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Component +open class BankService { + @PostAuthorize("returnObject.owner == authentication.name") + fun readAccount(val id: Long): Account { + // ... is only returned if the `Account` belongs to the logged in user + } +} +---- +==== + +This is meant to indicate that the method can only return the value if the provided expression `returnObject.owner == authentication.name` passes. +`returnObject` represents the `Account` object to be returned. + +You can then xref:servlet/test/method.adoc[test the class] to confirm it is enforcing the authorization rule: + +==== +.Java +[source,java,role="primary"] +---- +@Autowired +BankService bankService; + +@WithMockUser(username="owner") +@Test +void readAccountWhenOwnedThenReturns() { + Account account = this.bankService.readAccount("12345678"); + // ... assertions +} + +@WithMockUser(username="wrong") +@Test +void readAccountWhenNotOwnedThenAccessDenied() { + assertThatExceptionOfType(AccessDeniedException.class).isThrownBy( + () -> this.bankService.readAccount("12345678")); +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@WithMockUser(username="owner") +@Test +fun readAccountWhenOwnedThenReturns() { + val account: Account = this.bankService.readAccount("12345678") + // ... assertions +} + +@WithMockUser(username="wrong") +@Test +fun readAccountWhenNotOwnedThenAccessDenied() { + assertThatExceptionOfType(AccessDeniedException::class.java).isThrownBy { + this.bankService.readAccount("12345678") + } +} +---- +==== + +[TIP] +`@PostAuthorize` also can be a <>, be defined <>, and use xref:servlet/authorization/expression-based.adoc[SpEL Authorization Expressions]. + +`@PostAuthorize` is particularly helpful when defending against https://cheatsheetseries.owasp.org/cheatsheets/Insecure_Direct_Object_Reference_Prevention_Cheat_Sheet.html[Insecure Direct Object Reference]. +In fact, it can be defined as a <> like so: + +==== +.Java +[source,java,role="primary"] +---- +@Target({ ElementType.METHOD, ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +@PostAuthorize("returnObject.owner == authentication.name") +public @interface RequireOwnership {} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Target(ElementType.METHOD, ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@PostAuthorize("returnObject.owner == authentication.name") +annotation class RequireOwnership +---- +==== + +Allowing you to instead annotate the service in the following way: + +==== +.Java +[source,java,role="primary"] +---- +@Component +public class BankService { + @RequireOwnership + public Account readAccount(Long id) { + // ... is only returned if the `Account` belongs to the logged in user + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Component +open class BankService { + @RequireOwnership + fun readAccount(val id: Long): Account { + // ... is only returned if the `Account` belongs to the logged in user + } +} +---- +==== + +The result is that the above method will only return the `Account` if its `owner` attribute matches the logged-in user's `name`. +If not, Spring Security will throw an `AccessDeniedException` and return a 403 status code. + +[[use-prefilter]] +=== Filtering Method Parameters with `@PreFilter` + +[NOTE] +`@PreFilter` is not yet supported for Kotlin-specific data types; for that reason, only Java snippets are shown + +When Method Security is active, you can annotate a method with the {security-api-url}org/springframework/security/access/prepost/PreFilter.html[`@PreFilter`] annotation like so: + +==== +.Java +[source,java,role="primary"] +---- +@Component +public class BankService { + @PreFilter("filterObject.owner == authentication.name") + public Collection updateAccounts(Account... accounts) { + // ... `accounts` will only contain the accounts owned by the logged-in user + return updated; + } +} +---- +==== + +This is meant to filter out any values from `accounts` where the expression `filterObject.owner == authentication.name` fails. +`filterObject` represents each `account` in `accounts` and is used to test each `account`. + +You can then test the class in the following way to confirm it is enforcing the authorization rule: + +==== +.Java +[source,java,role="primary"] +---- +@Autowired +BankService bankService; + +@WithMockUser(username="owner") +@Test +void updateAccountsWhenOwnedThenReturns() { + Account ownedBy = ... + Account notOwnedBy = ... + Collection updated = this.bankService.updateAccounts(ownedBy, notOwnedBy); + assertThat(updated).containsOnly(ownedBy); +} +---- +==== + +[TIP] +`@PreFilter` also can be a <>, be defined <>, and use xref:servlet/authorization/expression-based.adoc[SpEL Authorization Expressions]. + +`@PreFilter` supports arrays, collections, maps, and streams (so long as the stream is still open). + +For example, the above `updateAccounts` declaration will function the same way as the following other four: + +==== +.Java +[source,java,role="primary"] +---- +@PreFilter("filterObject.owner == authentication.name") +public Collection updateAccounts(Account[] accounts) + +@PreFilter("filterObject.owner == authentication.name") +public Collection updateAccounts(Collection accounts) + +@PreFilter("filterObject.value.owner == authentication.name") +public Collection updateAccounts(Map accounts) + +@PreFilter("filterObject.owner == authentication.name") +public Collection updateAccounts(Stream accounts) +---- +==== + +The result is that the above method will only have the `Account` instances where their `owner` attribute matches the logged-in user's `name`. + +[[use-postfilter]] +=== Filtering Method Results with `@PostFilter` + +[NOTE] +`@PostFilter` is not yet supported for Kotlin-specific data types; for that reason, only Java snippets are shown + +When Method Security is active, you can annotate a method with the {security-api-url}org/springframework/security/access/prepost/PostFilter.html[`@PostFilter`] annotation like so: + +==== +.Java +[source,java,role="primary"] +---- +@Component +public class BankService { + @PostFilter("filterObject.owner == authentication.name") + public Collection readAccounts(String... ids) { + // ... the return value will be filtered to only contain the accounts owned by the logged-in user + return accounts; + } +} +---- +==== + +This is meant to filter out any values from the return value where the expression `filterObject.owner == authentication.name` fails. +`filterObject` represents each `account` in `accounts` and is used to test each `account`. + +You can then test the class like so to confirm it is enforcing the authorization rule: + +==== +.Java +[source,java,role="primary"] +---- +@Autowired +BankService bankService; + +@WithMockUser(username="owner") +@Test +void readAccountsWhenOwnedThenReturns() { + Collection accounts = this.bankService.updateAccounts("owner", "not-owner"); + assertThat(accounts).hasSize(1); + assertThat(accounts.get(0).getOwner()).isEqualTo("owner"); +} +---- +==== + +[TIP] +`@PostFilter` also can be a <>, be defined <>, and use xref:servlet/authorization/expression-based.adoc[SpEL Authorization Expressions]. + +`@PostFilter` supports arrays, collections, maps, and streams (so long as the stream is still open). + +For example, the above `readAccounts` declaration will function the same way as the following other three: + +```java +@PostFilter("filterObject.owner == authentication.name") +public Account[] readAccounts(String... ids) + +@PostFilter("filterObject.value.owner == authentication.name") +public Map readAccounts(String... ids) + +@PostFilter("filterObject.owner == authentication.name") +public Stream readAccounts(String... ids) +``` + +The result is that the above method will return the `Account` instances where their `owner` attribute matches the logged-in user's `name`. + +[NOTE] +In-memory filtering can obviously be expensive, and so be considerate of whether it is better to xref:servlet/integrations/data.adoc[filter the data in the data layer] instead. + +[[use-secured]] +=== Authorizing Method Invocation with `@Secured` + +{security-api-url}org/springframework/security/access/annotation/Secured.html[`@Secured`] is a legacy option for authorizing invocations. +<> supercedes it and is recommended instead. + +To use the `@Secured` annotation, you should first change your Method Security declaration to enable it like so: + +==== +.Java +[source,java,role="primary"] +---- +@EnableMethodSecurity(securedEnabled = true) +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableMethodSecurity(securedEnabled = true) +---- .Xml [source,xml,role="secondary"] @@ -126,28 +713,27 @@ class MethodSecurityConfig { ---- ==== -or JSR-250 using: +This will cause Spring Security to publish <> that authorizes methods, classes, and interfaces annotated with `@Secured`. + +[[use-jsr250]] +=== Authorizing Method Invocation with JSR-250 Annotations + +In case you would like to use https://jcp.org/en/jsr/detail?id=250[JSR-250] annotations, Spring Security also supports that. +<> has more expressive power and is thus recommended. + +To use the JSR-250 annotations, you should first change your Method Security declaration to enable them like so: -.JSR-250 Configuration ==== .Java [source,java,role="primary"] ---- -@Configuration @EnableMethodSecurity(jsr250Enabled = true) -public class MethodSecurityConfig { - // ... -} ---- .Kotlin [source,kotlin,role="secondary"] ---- -@Configuration @EnableMethodSecurity(jsr250Enabled = true) -class MethodSecurityConfig { - // ... -} ---- .Xml @@ -157,12 +743,393 @@ class MethodSecurityConfig { ---- ==== -=== Customizing Authorization +This will cause Spring Security to publish <> that authorizes methods, classes, and interfaces annotated with `@RolesAllowed`, `@PermitAll`, and `@DenyAll`. -Spring Security's `@PreAuthorize`, `@PostAuthorize`, `@PreFilter`, and `@PostFilter` ship with rich expression-based support. -[[jc-method-security-custom-expression-handler]] -If you need to customize the way that expressions are handled, you can expose a custom `MethodSecurityExpressionHandler`, like so: +[[class-or-interface-annotations]] +=== Declaring Annotations at the Class or Interface Level + +It's also supported to have Method Security annotations at the class and interface level. + +If it is at the class level like so: + +==== +.Java +[source,java,role="primary"] +---- +@Controller +@PreAuthorize("hasAuthority('ROLE_USER')") +public class MyController { + @GetMapping("/endpoint") + public String endpoint() { ... } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +@PreAuthorize("hasAuthority('ROLE_USER')") +open class MyController { + @GetMapping("/endpoint") + fun endpoint(): String { ... } +} +---- +==== + +then all methods inherit the class-level behavior. + +Or, if it's declared like the following at both the class and method level: + +==== +.Java +[source,java,role="primary"] +---- +@Controller +@PreAuthorize("hasAuthority('ROLE_USER')") +public class MyController { + @GetMapping("/endpoint") + @PreAuthorize("hasAuthority('ROLE_ADMIN')") + public String endpoint() { ... } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +@PreAuthorize("hasAuthority('ROLE_USER')") +open class MyController { + @GetMapping("/endpoint") + @PreAuthorize("hasAuthority('ROLE_ADMIN')") + fun endpoint(): String { ... } +} +---- +==== + +then methods declaring the annotation override the class-level annotation. + +The same is true for interfaces, with the exception that if a class inherits the annotation from two different interfaces, then startup will fail. +This is because Spring Security has no way to tell which one you want to use. + +In cases like this, you can resolve the ambiguity by adding the annotation to the concrete method. + +[[meta-annotations]] +=== Using Meta Annotations + +Method Security supports meta annotations. +This means that you can take any annotation and improve readability based on your application-specific use cases. + +For example, you can simplify `@PreAuthorize("hasRole('ADMIN')")` to `@IsAdmin` like so: + +==== +.Java +[source,java,role="primary"] +---- +@Target({ ElementType.METHOD, ElementType.TYPE }) +@Retention(RetentionPolicy.RUNTIME) +@PreAuthorize("hasRole('ADMIN')") +public @interface IsAdmin {} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Target(ElementType.METHOD, ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +@PreAuthorize("hasRole('ADMIN')") +annotation class IsAdmin +---- +==== + +And the result is that on your secured methods you can now do the following instead: + +==== +.Java +[source,java,role="primary"] +---- +@Component +public class BankService { + @IsAdmin + public Account readAccount(Long id) { + // ... is only returned if the `Account` belongs to the logged in user + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Component +open class BankService { + @IsAdmin + fun readAccount(val id: Long): Account { + // ... is only returned if the `Account` belongs to the logged in user + } +} +---- +==== + +This results in more readable method definitions. + +[[enable-annotation]] +=== Enabling Certain Annotations + +You can turn off ``@EnableMethodSecurity``'s pre-configuration and replace it with you own. +You may choose to do this if you want to <> or `Pointcut`. +Or you may simply want to only enable a specific annotation, like `@PostAuthorize`. + +You can do this in the following way: + +.Only @PostAuthorize Configuration +==== +.Java +[source,java,role="primary"] +---- +@Configuration +@EnableMethodSecurity(prePostEnabled = false) +class MethodSecurityConfig { + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + Advisor postAuthorize() { + return AuthorizationManagerBeforeMethodInterceptor.postAuthorize(); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Configuration +@EnableMethodSecurity(prePostEnabled = false) +class MethodSecurityConfig { + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + fun postAuthorize() : Advisor { + return AuthorizationManagerBeforeMethodInterceptor.postAuthorize() + } +} +---- + +.Xml +[source,xml,role="secondary"] +---- + + + + + +---- +==== + +The above snippet achieves this by first disabling Method Security's pre-configurations and then publishing <> itself. + +[[use-intercept-methods]] +== Authorizing with `` + +While using Spring Security's <> is preferred for method security, you can also use XML to declare bean authorization rules. + +If you need to declare it in your XML configuration instead, you can use xref:servlet/appendix/namespace/method-security.adoc#nsa-intercept-methods[``] like so: + +==== +.Xml +[source,xml,role="primary"] +---- + + + + + + +---- +==== + +[NOTE] +This only supports matching method by prefix or by name. +If your needs are more complex than that, <> instead. + +[[use-programmatic-authorization]] +== Authorizing Methods Programmatically + +As you've already seen, there are several ways that you can specify non-trivial authorization rules using xref:servlet/authorization/expression-based.adoc[Method Security SpEL expressions]. + +There are a number of ways that you can instead allow your logic to be Java-based instead of SpEL-based. +This gives use access the entire Java language for increased testability and flow control. + +=== Using a Custom Bean in SpEL + +The first way to authorize a method programmatically is a two-step process. + +First, declare a bean that has a method that takes a `MethodSecurityExpressionOperations` instance like the following: + +==== +.Java +[source,java,role="primary"] +---- +@Component("authz") +public class AuthorizationLogic { + public boolean decide(MethodSecurityExpressionOperations operations) { + // ... authorization logic + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Component("authz") +open class AuthorizationLogic { + fun decide(val operations: MethodSecurityExpressionOperations): boolean { + // ... authorization logic + } +} +---- +==== + +Then, reference that bean in your annotations in the following way: + +==== +.Java +[source,java,role="primary"] +---- +@Controller +public class MyController { + @PreAuthorize("@authz.decide(#root)") + @GetMapping("/endpoint") + public String endpoint() { + // ... + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Controller +open class MyController { + @PreAuthorize("@authz.decide(#root)") + @GetMapping("/endpoint") + fun String endpoint() { + // ... + } +} +---- +==== + +Spring Security will invoke the given method on that bean for each method invocation. + +What's nice about this is all your authorization logic is in a separate class that can be independently unit tested and verified for correctness. +It also has access to the full Java language. + +[[custom-authorization-managers]] +=== Using a Custom Authorization Manager + +The second way to authorize a method programmatically is two create a custom xref:servlet/authorization/architecture.adoc#_the_authorizationmanager[`AuthorizationManager`]. + +First, declare an authorization manager instance, perhaps like this one: + +==== +.Java +[source,java,role="primary"] +---- +@Component +public class MyAuthorizationManager implements AuthorizationManager { + public AuthorizationDecision check(Supplier authentication, MethodInvocation invocation) { + // ... authorization logic + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Component("authz") +open class MyAuthorizationManager: AuthorizationManager { + fun check(val authentication: Supplier, val invocation: MethodInvocation): AuthorizationDecision { + // ... authorization logic + } +} +---- +==== + +Then, publish the method interceptor with a pointcut that corresponds to when you want that `AuthorizationManager` to run. +For example, you could replace how `@PreAuthorize` and `@PostAuthorize` work like so: + +.Only @PostAuthorize Configuration +==== +.Java +[source,java,role="primary"] +---- +@Configuration +@EnableMethodSecurity(prePostEnabled = false) +class MethodSecurityConfig { + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + Advisor postAuthorize(MyAuthorizationManager manager) { + return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(manager); + } + + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + Advisor postAuthorize(MyAuthorizationManager manager) { + return AuthorizationManagerAfterMethodInterceptor.postAuthorize(manager); + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@Configuration +@EnableMethodSecurity(prePostEnabled = false) +class MethodSecurityConfig { + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + fun preAuthorize(val manager: MyAuthorizationManager) : Advisor { + return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(manager) + } + + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + fun postAuthorize(val manager: MyAuthorizationManager) : Advisor { + return AuthorizationManagerAfterMethodInterceptor.postAuthorize(manager) + } +} +---- + +.Xml +[source,xml,role="secondary"] +---- + + + + + + + + + + + +---- +==== + +[TIP] +==== +You can place your interceptor in between Spring Security method interceptors using the order constants specified in `AuthorizationInterceptorsOrder`. +==== + +[[customizing-expression-handling]] +=== Customizing Expression Handling + +Or, third, you can customize how each SpEL expression is handled. +To do that, you can expose a custom {security-api-url}org.springframework.security.access.expression.method.MethodSecurityExpressionHandler.html[`MethodSecurityExpressionHandler`], like so: .Custom MethodSecurityExpressionHandler ==== @@ -170,9 +1137,9 @@ If you need to customize the way that expressions are handled, you can expose a [source,java,role="primary"] ---- @Bean -static MethodSecurityExpressionHandler methodSecurityExpressionHandler() { +static MethodSecurityExpressionHandler methodSecurityExpressionHandler(RoleHierarchy roleHierarchy) { DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler(); - handler.setTrustResolver(myCustomTrustResolver); + handler.setRoleHierarchy(roleHierarchy); return handler; } ---- @@ -182,9 +1149,9 @@ static MethodSecurityExpressionHandler methodSecurityExpressionHandler() { ---- companion object { @Bean - fun methodSecurityExpressionHandler() : MethodSecurityExpressionHandler { + fun methodSecurityExpressionHandler(val roleHierarchy: RoleHierarchy) : MethodSecurityExpressionHandler { val handler = DefaultMethodSecurityExpressionHandler(); - handler.setTrustResolver(myCustomTrustResolver); + handler.setRoleHierarchy(roleHierarchy); return handler; } } @@ -199,7 +1166,7 @@ companion object { - + ---- ==== @@ -209,261 +1176,264 @@ companion object { We expose `MethodSecurityExpressionHandler` using a `static` method to ensure that Spring publishes it before it initializes Spring Security's method security `@Configuration` classes ==== -Also, for role-based authorization, Spring Security adds a default `ROLE_` prefix, which is uses when evaluating expressions like `hasRole`. +You can also <> to add your own custom authorization expressions beyond the defaults. -[[jc-method-security-custom-granted-authority-defaults]] -You can configure the authorization rules to use a different prefix by exposing a `GrantedAuthorityDefaults` bean, like so: +[[use-aspectj]] +== Authorizing with AspectJ + +[[match-by-pointcut]] +=== Matching Methods with Custom Pointcuts + +Being built on Spring AOP, you can declare patterns that are not related to annotations, similar to xref:servlet/authorization/authorize-http-requests.adoc[request-level authorization]. +This has the potential advantage of centralizing method-level authorization rules. + +For example, you can use publish your own `Advisor` or use xref:servlet/appendix/namespace/method-security.adoc#nsa-protect-pointcut[``] to match AOP expressions to authorization rules for your service layer like so: -.Custom MethodSecurityExpressionHandler ==== .Java [source,java,role="primary"] ---- +import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasRole; + @Bean -static GrantedAuthorityDefaults grantedAuthorityDefaults() { - return new GrantedAuthorityDefaults("MYPREFIX_"); +@Role(BeanDefinition.ROLE_INFRASTRUCTURE) +static Advisor protectServicePointcut() { + JdkRegexpMethodPointcut pattern = new JdkRegexpMethodPointcut(); + pattern.setPattern("execution(* com.mycompany.*Service.*(..))"); + return new AuthorizationManagerBeforeMethodInterceptor(pattern, hasRole("USER")); } ---- .Kotlin [source,kotlin,role="secondary"] ---- +import static org.springframework.security.authorization.AuthorityAuthorizationManager.hasRole; + companion object { - @Bean - fun grantedAuthorityDefaults() : GrantedAuthorityDefaults { - return GrantedAuthorityDefaults("MYPREFIX_"); - } + @Bean + @Role(BeanDefinition.ROLE_INFRASTRUCTURE) + fun protectServicePointcut(): Advisor { + var pattern = JdkRegexpMethodPointcut(); + pattern.setPattern("execution(* com.mycompany.*Service.*(..))"); + return new AuthorizationManagerBeforeMethodInterceptor(pattern, hasRole("USER")); + } } ---- -.Xml -[source,xml,role="secondary"] +[source,xml] ---- - - - - - + + + ---- ==== -[TIP] -==== -We expose `GrantedAuthorityDefaults` using a `static` method to ensure that Spring publishes it before it initializes Spring Security's method security `@Configuration` classes -==== +[[weave-aspectj]] +=== Integrate with AspectJ Byte-weaving -[[jc-method-security-custom-authorization-manager]] -=== Custom Authorization Managers +Performance can at times be enhanced by using AspectJ to weave Spring Security advice into the byte code of your beans. -Method authorization is a combination of before- and after-method authorization. +After setting up AspectJ, you can quite simply state in the `@EnableMethodSecurity` annotation or `` element that you are using AspectJ: -[NOTE] -==== -Before-method authorization is performed before the method is invoked. -If that authorization denies access, the method is not invoked, and an `AccessDeniedException` is thrown. -After-method authorization is performed after the method is invoked, but before the method returns to the caller. -If that authorization denies access, the value is not returned, and an `AccessDeniedException` is thrown -==== - -To recreate what adding `@EnableMethodSecurity` does by default, you would publish the following configuration: - -.Full Pre-post Method Security Configuration ==== .Java [source,java,role="primary"] ---- -@Configuration -@EnableMethodSecurity(prePostEnabled = false) -class MethodSecurityConfig { - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - Advisor preFilterAuthorizationMethodInterceptor() { - return new PreFilterAuthorizationMethodInterceptor(); - } - - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - Advisor preAuthorizeAuthorizationMethodInterceptor() { - return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(); - } - - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - Advisor postAuthorizeAuthorizationMethodInterceptor() { - return AuthorizationManagerAfterMethodInterceptor.postAuthorize(); - } - - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - Advisor postFilterAuthorizationMethodInterceptor() { - return new PostFilterAuthorizationMethodInterceptor(); - } -} +@EnableMethodSecurity(mode=AdviceMode.ASPECTJ) ---- .Kotlin [source,kotlin,role="secondary"] ---- -@Configuration -@EnableMethodSecurity(prePostEnabled = false) -class MethodSecurityConfig { - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - fun preFilterAuthorizationMethodInterceptor() : Advisor { - return PreFilterAuthorizationMethodInterceptor(); - } - - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - fun preAuthorizeAuthorizationMethodInterceptor() : Advisor { - return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(); - } - - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - fun postAuthorizeAuthorizationMethodInterceptor() : Advisor { - return AuthorizationManagerAfterMethodInterceptor.postAuthorize(); - } - - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - fun postFilterAuthorizationMethodInterceptor() : Advisor { - return PostFilterAuthorizationMethodInterceptor(); - } -} +@EnableMethodSecurity(mode=AdviceMode.ASPECTJ) ---- .Xml [source,xml,role="secondary"] ---- - - - - - - - - + ---- ==== -Notice that Spring Security's method security is built using Spring AOP. -So, interceptors are invoked based on the order specified. -This can be customized by calling `setOrder` on the interceptor instances like so: +And the result will be that Spring Security will publish its advisors as AspectJ advice so that they can be woven in accordingly. + +[[migration-enableglobalmethodsecurity]] +== Migrating from `@EnableGlobalMethodSecurity` + +If you are using `@EnableGlobalMethodSecurity`, you should migrate to `@EnableMethodSecurity`. + +[[servlet-replace-globalmethodsecurity-with-methodsecurity]] +=== Replace xref:servlet/authorization/method-security.adoc#jc-enable-global-method-security[global method security] with xref:servlet/authorization/method-security.adoc#jc-enable-method-security[method security] + +{security-api-url}org/springframework/security/config/annotation/method/configuration/EnableGlobalMethodSecurity.html[`@EnableGlobalMethodSecurity`] and xref:servlet/appendix/namespace/method-security.adoc#nsa-global-method-security[``] are deprecated in favor of {security-api-url}org/springframework/security/config/annotation/method/configuration/EnableMethodSecurity.html[`@EnableMethodSecurity`] and xref:servlet/appendix/namespace/method-security.adoc#nsa-method-security[``], respectively. +The new annotation and XML element activate Spring's xref:servlet/authorization/method-security.adoc#jc-enable-method-security[pre-post annotations] by default and use `AuthorizationManager` internally. + +This means that the following two listings are functionally equivalent: -.Publish Custom Advisor ==== .Java [source,java,role="primary"] ---- -@Bean -@Role(BeanDefinition.ROLE_INFRASTRUCTURE) -Advisor postFilterAuthorizationMethodInterceptor() { - PostFilterAuthorizationMethodInterceptor interceptor = new PostFilterAuthorizationMethodInterceptor(); - interceptor.setOrder(AuthorizationInterceptorOrders.POST_AUTHORIZE.getOrder() - 1); - return interceptor; -} +@EnableGlobalMethodSecurity(prePostEnabled = true) ---- .Kotlin [source,kotlin,role="secondary"] ---- -@Bean -@Role(BeanDefinition.ROLE_INFRASTRUCTURE) -fun postFilterAuthorizationMethodInterceptor() : Advisor { - val interceptor = PostFilterAuthorizationMethodInterceptor(); - interceptor.setOrder(AuthorizationInterceptorOrders.POST_AUTHORIZE.getOrder() - 1); - return interceptor; -} +@EnableGlobalMethodSecurity(prePostEnabled = true) ---- .Xml [source,xml,role="secondary"] ---- - - - + ---- ==== -You may want to only support `@PreAuthorize` in your application, in which case you can do the following: +and: - -.Only @PreAuthorize Configuration ==== .Java [source,java,role="primary"] ---- -@Configuration -@EnableMethodSecurity(prePostEnabled = false) -class MethodSecurityConfig { - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - Advisor preAuthorize() { - return AuthorizationManagerBeforeMethodInterceptor.preAuthorize(); - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Configuration -@EnableMethodSecurity(prePostEnabled = false) -class MethodSecurityConfig { - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - fun preAuthorize() : Advisor { - return AuthorizationManagerBeforeMethodInterceptor.preAuthorize() - } -} ----- - -.Xml -[source,xml,role="secondary"] ----- - - - - - ----- -==== - -Or, you may have a custom before-method `AuthorizationManager` that you want to add to the list. - -In this case, you will need to tell Spring Security both the `AuthorizationManager` and to which methods and classes your authorization manager applies. - -Thus, you can configure Spring Security to invoke your `AuthorizationManager` in between `@PreAuthorize` and `@PostAuthorize` like so: - -.Custom Before Advisor -==== - -.Java -[source,java,role="primary"] ----- -@Configuration @EnableMethodSecurity -class MethodSecurityConfig { - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - public Advisor customAuthorize() { - JdkRegexpMethodPointcut pattern = new JdkRegexpMethodPointcut(); - pattern.setPattern("org.mycompany.myapp.service.*"); - AuthorizationManager rule = AuthorityAuthorizationManager.isAuthenticated(); - AuthorizationManagerBeforeMethodInterceptor interceptor = new AuthorizationManagerBeforeMethodInterceptor(pattern, rule); - interceptor.setOrder(AuthorizationInterceptorsOrder.PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1); - return interceptor; +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableMethodSecurity +---- + +.Xml +[source,xml,role="secondary"] +---- + +---- +==== + +For applications not using the pre-post annotations, make sure to turn it off to avoid activating unwanted behavior. + +For example, a listing like: + +==== +.Java +[source,java,role="primary"] +---- +@EnableGlobalMethodSecurity(securedEnabled = true) +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableGlobalMethodSecurity(securedEnabled = true) +---- + +.Xml +[source,xml,role="secondary"] +---- + +---- +==== + +should change to: + +==== +.Java +[source,java,role="primary"] +---- +@EnableMethodSecurity(securedEnabled = true, prePostEnabled = false) +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@EnableMethodSecurity(securedEnabled = true, prePostEnabled = false) +---- + +.Xml +[source,xml,role="secondary"] +---- + +---- +==== + +=== Use a Custom `@Bean` instead of subclassing `DefaultMethodSecurityExpressionHandler` + +As a performance optimization, a new method was introduced to `MethodSecurityExpressionHandler` that takes a `Supplier` instead of an `Authentication`. + +This allows Spring Security to defer the lookup of the `Authentication`, and is taken advantage of automatically when you use `@EnableMethodSecurity` instead of `@EnableGlobalMethodSecurity`. + +However, let's say that your code extends `DefaultMethodSecurityExpressionHandler` and overrides `createSecurityExpressionRoot(Authentication, MethodInvocation)` to return a custom `SecurityExpressionRoot` instance. +This will no longer work because the arrangement that `@EnableMethodSecurity` sets up calls `createEvaluationContext(Supplier, MethodInvocation)` instead. + +Happily, such a level of customization is often unnecessary. +Instead, you can create a custom bean with the authorization methods that you need. + +For example, let's say you are wanting a custom evaluation of `@PostAuthorize("hasAuthority('ADMIN')")`. +You can create a custom `@Bean` like this one: + +==== +.Java +[source,java,role="primary"] +---- +class MyAuthorizer { + boolean isAdmin(MethodSecurityExpressionOperations root) { + boolean decision = root.hasAuthority("ADMIN"); + // custom work ... + return decision; + } +} +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +class MyAuthorizer { + fun isAdmin(val root: MethodSecurityExpressionOperations): boolean { + val decision = root.hasAuthority("ADMIN"); + // custom work ... + return decision; + } +} +---- +==== + +and then refer to it in the annotation like so: + +==== +.Java +[source,java,role="primary"] +---- +@PreAuthorize("@authz.isAdmin(#root)") +---- + +.Kotlin +[source,kotlin,role="secondary"] +---- +@PreAuthorize("@authz.isAdmin(#root)") +---- +==== + +[[subclass-defaultmethodsecurityexpressionhandler]] +==== I'd still prefer to subclass `DefaultMethodSecurityExpressionHandler` + +If you must continue subclassing `DefaultMethodSecurityExpressionHandler`, you can still do so. +Instead, override the `createEvaluationContext(Supplier, MethodInvocation)` method like so: + +==== +.Java +[source,java,role="primary"] +---- +@Component +class MyExpressionHandler extends DefaultMethodSecurityExpressionHandler { + @Override + public EvaluationContext createEvaluationContext(Supplier authentication, MethodInvocation mi) { + StandardEvaluationContext context = (StandardEvaluationContext) super.createEvaluationContext(authentication, mi); + MethodSecurityExpressionOperations delegate = (MethodSecurityExpressionOperations) context.getRootObject().getValue(); + MySecurityExpressionRoot root = new MySecurityExpressionRoot(delegate); + context.setRootObject(root); + return context; } } ---- @@ -471,472 +1441,21 @@ class MethodSecurityConfig { .Kotlin [source,kotlin,role="secondary"] ---- -@Configuration -@EnableMethodSecurity -class MethodSecurityConfig { - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - fun customAuthorize() : Advisor { - val pattern = JdkRegexpMethodPointcut(); - pattern.setPattern("org.mycompany.myapp.service.*"); - val rule = AuthorityAuthorizationManager.isAuthenticated(); - val interceptor = AuthorizationManagerBeforeMethodInterceptor(pattern, rule); - interceptor.setOrder(AuthorizationInterceptorsOrder.PRE_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1); - return interceptor; - } -} ----- - -.Xml -[source,xml,role="secondary"] ----- - - - - - - - - - - - - - - - ----- -==== - -[TIP] -==== -You can place your interceptor in between Spring Security method interceptors using the order constants specified in `AuthorizationInterceptorsOrder`. -==== - -The same can be done for after-method authorization. -After-method authorization is generally concerned with analysing the return value to verify access. - -For example, you might have a method that confirms that the account requested actually belongs to the logged-in user like so: - -.@PostAuthorize example -==== -.Java -[source,java,role="primary"] ----- -public interface BankService { - - @PreAuthorize("hasRole('USER')") - @PostAuthorize("returnObject.owner == authentication.name") - Account readAccount(Long id); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -interface BankService { - - @PreAuthorize("hasRole('USER')") - @PostAuthorize("returnObject.owner == authentication.name") - fun readAccount(id : Long) : Account -} ----- -==== - -You can supply your own `AuthorizationMethodInterceptor` to customize how access to the return value is evaluated. - -For example, if you have your own custom annotation, you can configure it like so: - - -.Custom After Advisor -==== -.Java -[source,java,role="primary"] ----- -@Configuration -@EnableMethodSecurity -class MethodSecurityConfig { - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - public Advisor customAuthorize(AuthorizationManager rules) { - AnnotationMatchingPointcut pattern = new AnnotationMatchingPointcut(MySecurityAnnotation.class); - AuthorizationManagerAfterMethodInterceptor interceptor = new AuthorizationManagerAfterMethodInterceptor(pattern, rules); - interceptor.setOrder(AuthorizationInterceptorsOrder.POST_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1); - return interceptor; - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Configuration -@EnableMethodSecurity -class MethodSecurityConfig { - @Bean - @Role(BeanDefinition.ROLE_INFRASTRUCTURE) - fun customAuthorize(rules : AuthorizationManager) : Advisor { - val pattern = AnnotationMatchingPointcut(MySecurityAnnotation::class.java); - val interceptor = AuthorizationManagerAfterMethodInterceptor(pattern, rules); - interceptor.setOrder(AuthorizationInterceptorsOrder.POST_AUTHORIZE_ADVISOR_ORDER.getOrder() + 1); - return interceptor; - } -} ----- - -.Xml -[source,xml,role="secondary"] ----- - - - - - - - - - - - - - - - ----- -==== - -and it will be invoked after the `@PostAuthorize` interceptor. - -[[jc-enable-global-method-security]] -== EnableGlobalMethodSecurity - -We can enable annotation-based security by using the `@EnableGlobalMethodSecurity` annotation on any `@Configuration` instance. -The following example enables Spring Security's `@Secured` annotation: - -==== -.Java -[source,java,role="primary"] ----- -@Configuration -@EnableGlobalMethodSecurity(securedEnabled = true) -public class MethodSecurityConfig { -// ... -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Configuration -@EnableGlobalMethodSecurity(securedEnabled = true) -open class MethodSecurityConfig { - // ... -} ----- -==== - -Adding an annotation to a method (on a class or interface) would then limit the access to that method accordingly. -Spring Security's native annotation support defines a set of attributes for the method. -These are passed to the `AccessDecisionManager` for it to make the actual decision: - -==== -.Java -[source,java,role="primary"] ----- -public interface BankService { - -@Secured("IS_AUTHENTICATED_ANONYMOUSLY") -public Account readAccount(Long id); - -@Secured("IS_AUTHENTICATED_ANONYMOUSLY") -public Account[] findAccounts(); - -@Secured("ROLE_TELLER") -public Account post(Account account, double amount); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -interface BankService { - @Secured("IS_AUTHENTICATED_ANONYMOUSLY") - fun readAccount(id: Long): Account - - @Secured("IS_AUTHENTICATED_ANONYMOUSLY") - fun findAccounts(): Array - - @Secured("ROLE_TELLER") - fun post(account: Account, amount: Double): Account -} ----- -==== - -Support for JSR-250 annotations can be enabled by using: - -==== -.Java -[source,java,role="primary"] ----- -@Configuration -@EnableGlobalMethodSecurity(jsr250Enabled = true) -public class MethodSecurityConfig { -// ... -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Configuration -@EnableGlobalMethodSecurity(jsr250Enabled = true) -open class MethodSecurityConfig { - // ... -} ----- -==== - -These are standards-based and let simple role-based constraints be applied but do not have the power Spring Security's native annotations. -To use the new expression-based syntax, you would use: - -==== -.Java -[source,java,role="primary"] ----- -@Configuration -@EnableGlobalMethodSecurity(prePostEnabled = true) -public class MethodSecurityConfig { -// ... -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Configuration -@EnableGlobalMethodSecurity(prePostEnabled = true) -open class MethodSecurityConfig { - // ... -} ----- -==== - -The equivalent Java code is: - -==== -.Java -[source,java,role="primary"] ----- -public interface BankService { - -@PreAuthorize("isAnonymous()") -public Account readAccount(Long id); - -@PreAuthorize("isAnonymous()") -public Account[] findAccounts(); - -@PreAuthorize("hasAuthority('ROLE_TELLER')") -public Account post(Account account, double amount); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -interface BankService { - @PreAuthorize("isAnonymous()") - fun readAccount(id: Long): Account - - @PreAuthorize("isAnonymous()") - fun findAccounts(): Array - - @PreAuthorize("hasAuthority('ROLE_TELLER')") - fun post(account: Account, amount: Double): Account -} ----- -==== - -== GlobalMethodSecurityConfiguration - -Sometimes, you may need to perform operations that are more complicated than are possible with the `@EnableGlobalMethodSecurity` annotation. -For these instances, you can extend the `GlobalMethodSecurityConfiguration`, ensuring that the `@EnableGlobalMethodSecurity` annotation is present on your subclass. -For example, if you wanted to provide a custom `MethodSecurityExpressionHandler`, you could use the following configuration: - -==== -.Java -[source,java,role="primary"] ----- -@Configuration -@EnableGlobalMethodSecurity(prePostEnabled = true) -public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { - @Override - protected MethodSecurityExpressionHandler createExpressionHandler() { - // ... create and return custom MethodSecurityExpressionHandler ... - return expressionHandler; - } -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -@Configuration -@EnableGlobalMethodSecurity(prePostEnabled = true) -open class MethodSecurityConfig : GlobalMethodSecurityConfiguration() { - override fun createExpressionHandler(): MethodSecurityExpressionHandler { - // ... create and return custom MethodSecurityExpressionHandler ... - return expressionHandler +@Component +class MyExpressionHandler: DefaultMethodSecurityExpressionHandler { + override fun createEvaluationContext(val authentication: Supplier, + val mi: MethodInvocation): EvaluationContext { + val context = super.createEvaluationContext(authentication, mi) as StandardEvaluationContext + val delegate = context.getRootObject().getValue() as MethodSecurityExpressionOperations + val root = MySecurityExpressionRoot(delegate) + context.setRootObject(root); + return context; } } ---- ==== -For additional information about methods that can be overridden, see the Javadoc for the {security-api-url}org/springframework/security/config/annotation/method/configuration/GlobalMethodSecurityConfiguration.html[`GlobalMethodSecurityConfiguration`] class. +== Further Reading -[[ns-global-method]] -== The Element -This element is used to enable annotation-based security in your application (by setting the appropriate attributes on the element) and to group together security pointcut declarations that are applied across your entire application context. -You should only declare one `` element. -The following declaration enables support for Spring Security's `@Secured`: - -==== -[source,xml] ----- - ----- -==== - -Adding an annotation to a method (on a class or interface) would then limit the access to that method accordingly. -Spring Security's native annotation support defines a set of attributes for the method. -These are passed to the `AccessDecisionManager` for it to make the actual decision. -The following example shows the `@Secured` annotation in a typical interface: - -==== -.Java -[source,java,role="primary"] ----- -public interface BankService { - -@Secured("IS_AUTHENTICATED_ANONYMOUSLY") -public Account readAccount(Long id); - -@Secured("IS_AUTHENTICATED_ANONYMOUSLY") -public Account[] findAccounts(); - -@Secured("ROLE_TELLER") -public Account post(Account account, double amount); -} ----- - - -.Kotlin -[source,kotlin,role="secondary"] ----- -interface BankService { - @Secured("IS_AUTHENTICATED_ANONYMOUSLY") - fun readAccount(id: Long): Account - - @Secured("IS_AUTHENTICATED_ANONYMOUSLY") - fun findAccounts(): Array - - @Secured("ROLE_TELLER") - fun post(account: Account, amount: Double): Account -} ----- -==== - -Support for JSR-250 annotations can be enabled by using: - -==== -[source,xml] ----- - ----- -==== - -These are standards-based and allow simple role-based constraints to be applied, but they do not have the power Spring Security's native annotations. -To use the expression-based syntax, use: - -==== -[source,xml] ----- - ----- -==== - -The equivalent Java code is: - -==== -.Java -[source,java,role="primary"] ----- -public interface BankService { - -@PreAuthorize("isAnonymous()") -public Account readAccount(Long id); - -@PreAuthorize("isAnonymous()") -public Account[] findAccounts(); - -@PreAuthorize("hasAuthority('ROLE_TELLER')") -public Account post(Account account, double amount); -} ----- - -.Kotlin -[source,kotlin,role="secondary"] ----- -interface BankService { - @PreAuthorize("isAnonymous()") - fun readAccount(id: Long): Account - - @PreAuthorize("isAnonymous()") - fun findAccounts(): Array - - @PreAuthorize("hasAuthority('ROLE_TELLER')") - fun post(account: Account, amount: Double): Account -} ----- -==== - -Expression-based annotations are a good choice if you need to define simple rules that go beyond checking the role names against the user's list of authorities. - -[NOTE] -==== -The annotated methods will only be secured for instances which are defined as Spring beans (in the same application context in which method-security is enabled). -If you want to secure instances which are not created by Spring (using the `new` operator, for example) then you need to use AspectJ. -==== - -[NOTE] -==== -You can enable more than one type of annotation in the same application, but only one type should be used for any interface or class as the behaviour will not be well-defined otherwise. -If two annotations are found which apply to a particular method, then only one of them will be applied. -==== - -[[ns-protect-pointcut]] -== Adding Security Pointcuts by using protect-pointcut - -`protect-pointcut` is particularly powerful, as it lets you apply security to many beans with only a simple declaration. -Consider the following example: - -==== -[source,xml] ----- - - - ----- -==== - -d. -This configuration protects all methods on beans declared in the application context whose classes are in the `com.mycompany` package and whose class names end in `Service`. -Only users with the `ROLE_USER` role can invoke these methods. -As with URL matching, the most specific matches must come first in the list of pointcuts, as the first matching expression is used. -Security annotations take precedence over pointcuts. +Now that you have secured your application's requests, please xref:servlet/authorization/authorize-http-requests.adoc[secure its requests] if you haven't already. +You can also read further on xref:servlet/test/index.adoc[testing your application] or on integrating Spring Security with other aspects of you application like xref:servlet/integrations/data.adoc[the data layer] or xref:servlet/integrations/observability.adoc[tracing and metrics]. diff --git a/docs/modules/ROOT/pages/servlet/authorization/secure-objects.adoc b/docs/modules/ROOT/pages/servlet/authorization/secure-objects.adoc deleted file mode 100644 index 84557b540c..0000000000 --- a/docs/modules/ROOT/pages/servlet/authorization/secure-objects.adoc +++ /dev/null @@ -1,143 +0,0 @@ - -[[secure-object-impls]] -= Secure Object Implementations - -This section covers how Spring Security handles Secure Object implementations. - -[[aop-alliance]] -== AOP Alliance (MethodInvocation) Security Interceptor -Prior to Spring Security 2.0, securing `MethodInvocation` instances needed a lot of boiler plate configuration. -Now the recommended approach for method security is to use xref:servlet/configuration/xml-namespace.adoc#ns-method-security[namespace configuration]. -This way, the method security infrastructure beans are configured automatically for you, so you need not know about the implementation classes. -We provide only a quick overview of the classes that are involved here. - -Method security is enforced by using a `MethodSecurityInterceptor`, which secures `MethodInvocation` instances. -Depending on the configuration approach, an interceptor may be specific to a single bean or shared between multiple beans. -The interceptor uses a `MethodSecurityMetadataSource` instance to obtain the configuration attributes that apply to a particular method invocation. -`MapBasedMethodSecurityMetadataSource` is used to store configuration attributes keyed by method names (which can be wildcarded) and will be used internally when the attributes are defined in the application context using the `` or `` elements. -Other implementations are used to handle annotation-based configuration. - -=== Explicit MethodSecurityInterceptor Configuration -You can configure a `MethodSecurityInterceptor` directly in your application context for use with one of Spring AOP's proxying mechanisms: - -==== -[source,xml] ----- - - - - - - - - - - - ----- -==== - -[[aspectj]] -== AspectJ (JoinPoint) Security Interceptor -The AspectJ security interceptor is very similar to the AOP Alliance security interceptor discussed in the previous section. -We discuss only the differences in this section. - -The AspectJ interceptor is named `AspectJSecurityInterceptor`. -Unlike the AOP Alliance security interceptor, which relies on the Spring application context to weave in the security interceptor through proxying, the `AspectJSecurityInterceptor` is woven in through the AspectJ compiler. -It would not be uncommon to use both types of security interceptors in the same application, with `AspectJSecurityInterceptor` being used for domain object instance security and the AOP Alliance `MethodSecurityInterceptor` being used for services layer security. - -We first consider how the `AspectJSecurityInterceptor` is configured in the Spring application context: - -==== -[source,xml] ----- - - - - - - - - - - - ----- -==== - -The two interceptors can share the same `securityMetadataSource`, as the `SecurityMetadataSource` works with `java.lang.reflect.Method` instances rather than an AOP library-specific class. -Your access decisions have access to the relevant AOP library-specific invocation (`MethodInvocation` or `JoinPoint`) and can consider a range of additional criteria (such as method arguments) when making access decisions. - -Next, you need to define an AspectJ `aspect`, as the following example shows: - -==== -[source,java] ----- - -package org.springframework.security.samples.aspectj; - -import org.springframework.security.access.intercept.aspectj.AspectJSecurityInterceptor; -import org.springframework.security.access.intercept.aspectj.AspectJCallback; -import org.springframework.beans.factory.InitializingBean; - -public aspect DomainObjectInstanceSecurityAspect implements InitializingBean { - - private AspectJSecurityInterceptor securityInterceptor; - - pointcut domainObjectInstanceExecution(): target(PersistableEntity) - && execution(public * *(..)) && !within(DomainObjectInstanceSecurityAspect); - - Object around(): domainObjectInstanceExecution() { - if (this.securityInterceptor == null) { - return proceed(); - } - - AspectJCallback callback = new AspectJCallback() { - public Object proceedWithObject() { - return proceed(); - } - }; - - return this.securityInterceptor.invoke(thisJoinPoint, callback); - } - - public AspectJSecurityInterceptor getSecurityInterceptor() { - return securityInterceptor; - } - - public void setSecurityInterceptor(AspectJSecurityInterceptor securityInterceptor) { - this.securityInterceptor = securityInterceptor; - } - - public void afterPropertiesSet() throws Exception { - if (this.securityInterceptor == null) - throw new IllegalArgumentException("securityInterceptor required"); - } - } -} ----- -==== - - -In the preceding example, the security interceptor is applied to every instance of `PersistableEntity`, which is an abstract class not shown (you can use any other class or `pointcut` expression you like). -For those curious, `AspectJCallback` is needed because the `proceed();` statement has special meaning only within an `around()` body. -The `AspectJSecurityInterceptor` calls this anonymous `AspectJCallback` class when it wants the target object to continue. - -You need to configure Spring to load the aspect and wire it with the `AspectJSecurityInterceptor`. -The following example shows a bean declaration that achieves this: - -==== -[source,xml] ----- - - - - ----- -==== - -Now you can create your beans from anywhere within your application, using whatever means you think fit (e.g. `new Person();`), and they have the security interceptor applied. diff --git a/docs/modules/ROOT/pages/servlet/oauth2/resource-server/index.adoc b/docs/modules/ROOT/pages/servlet/oauth2/resource-server/index.adoc index 52e991a0f4..3a3eae8ea7 100644 --- a/docs/modules/ROOT/pages/servlet/oauth2/resource-server/index.adoc +++ b/docs/modules/ROOT/pages/servlet/oauth2/resource-server/index.adoc @@ -27,7 +27,7 @@ The figure above builds off our xref:servlet/architecture.adoc#servlet-securityf image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the `/private` resource for which the user is not authorized. -image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] indicates that the unauthenticated request is _Denied_ by throwing an `AccessDeniedException`. +image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-http-requests.adoc[`AuthorizationFilter`] indicates that the unauthenticated request is _Denied_ by throwing an `AccessDeniedException`. image:{icondir}/number_3.png[] Since the user is not authenticated, xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates _Start Authentication_. The configured xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is an instance of {security-api-url}org/springframework/security/oauth2/server/resource/authentication/BearerTokenAuthenticationEntryPoint.html[`BearerTokenAuthenticationEntryPoint`], which sends a `WWW-Authenticate` header. diff --git a/docs/modules/ROOT/pages/servlet/saml2/login/overview.adoc b/docs/modules/ROOT/pages/servlet/saml2/login/overview.adoc index 2551206a09..b7a83a0daa 100644 --- a/docs/modules/ROOT/pages/servlet/saml2/login/overview.adoc +++ b/docs/modules/ROOT/pages/servlet/saml2/login/overview.adoc @@ -16,7 +16,7 @@ The figure above builds off our xref:servlet/architecture.adoc#servlet-securityf image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the `/private` resource, for which it is not authorized. -image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] indicates that the unauthenticated request is _Denied_ by throwing an `AccessDeniedException`. +image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-http-requests.adoc[`AuthorizationFilter`] indicates that the unauthenticated request is _Denied_ by throwing an `AccessDeniedException`. image:{icondir}/number_3.png[] Since the user lacks authorization, the xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates _Start Authentication_. The configured xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is an instance of {security-api-url}org/springframework/security/web/authentication/LoginUrlAuthenticationEntryPoint.html[`LoginUrlAuthenticationEntryPoint`], which redirects to <` generating endpoint>>, `Saml2WebSsoAuthenticationRequestFilter`.