This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Security 6.4.2!

Authorize HttpServletRequest with FilterSecurityInterceptor

FilterSecurityInterceptor is in the process of being replaced by AuthorizationFilter. Consider using that instead.

This section builds on Servlet Architecture and Implementation by digging deeper into how authorization works within Servlet based applications.

The FilterSecurityInterceptor provides authorization for HttpServletRequests. It is inserted into the FilterChainProxy as one of the Security Filters.

filtersecurityinterceptor
Figure 1. Authorize HttpServletRequest
  • number 1 First, the FilterSecurityInterceptor obtains an Authentication from the SecurityContextHolder.

  • number 2 Second, FilterSecurityInterceptor creates a FilterInvocation from the HttpServletRequest, HttpServletResponse, and FilterChain that are passed into the FilterSecurityInterceptor.

  • number 3 Next, it passes the FilterInvocation to SecurityMetadataSource to get the ConfigAttributes.

  • number 4 Finally, it passes the Authentication, FilterInvocation, and ConfigAttributes to the xref:servlet/authorization.adoc#authz-access-decision-manager`AccessDecisionManager`.

    • number 5 If authorization is denied, an AccessDeniedException is thrown. In this case the ExceptionTranslationFilter handles the AccessDeniedException.

    • number 6 If access is granted, FilterSecurityInterceptor continues with the FilterChain which allows the application to process normally.

By default, Spring Security’s authorization will require all requests to be authenticated. The explicit configuration looks like:

Every Request Must be Authenticated
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
	http
		// ...
		.authorizeRequests(authorize -> 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
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
	http
		// ...
		.authorizeRequests(authorize -> authorize                                  (1)
			.mvcMatchers("/resources/**", "/signup", "/about").permitAll()         (2)
			.mvcMatchers("/admin/**").hasRole("ADMIN")                             (3)
			.mvcMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")   (4)
			.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.

Apply FilterSecurityInterceptor to every request

By default, the FilterSecurityInterceptor only applies once to a request. This means that if a request is dispatched from a request that was already filtered, the FilterSecurityInterceptor will back-off and not perform any authorization checks. In some scenarios, you may want to apply the filter to every request. You can configure Spring Security to apply the authorization rules to every request by using the filterSecurityInterceptorOncePerRequest method:

Set filterSecurityInterceptorOncePerRequest to false
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    http
        .authorizeRequests((authorize) -> authorize
            .filterSecurityInterceptorOncePerRequest(false)
            .anyRequest.authenticated()
        )
        // ...

    return http.build();
}

You can also configure authorization based on the request dispatcher type:

Permit ASYNC dispatcher type
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    http
        .authorizeRequests((authorize) -> authorize
            .filterSecurityInterceptorOncePerRequest(false)
            .dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll()
            .anyRequest.authenticated()
        )
        // ...

    return http.build();
}