servlet-authorization-authorize-requests.md 6.4 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
# Authorize HttpServletRequest with FilterSecurityInterceptor

|   |`FilterSecurityInterceptor` is in the process of being replaced by [`AuthorizationFilter`](authorize-http-requests.html).<br/>Consider using that instead.|
|---|----------------------------------------------------------------------------------------------------------------------------------------------------------|

This section builds on [Servlet Architecture and Implementation](../architecture.html#servlet-architecture) by digging deeper into how [authorization](index.html#servlet-authorization) works within Servlet based applications.

The [`FilterSecurityInterceptor`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/access/intercept/FilterSecurityInterceptor.html) provides [authorization](index.html#servlet-authorization) for `HttpServletRequest`s.
It is inserted into the [FilterChainProxy](../architecture.html#servlet-filterchainproxy) as one of the [Security Filters](../architecture.html#servlet-security-filters).

![filtersecurityinterceptor](https://docs.spring.io/spring-security/reference/_images/servlet/authorization/filtersecurityinterceptor.png)

Figure 1. Authorize HttpServletRequest

* ![number 1](https://docs.spring.io/spring-security/reference/_images/icons/number_1.png) First, the `FilterSecurityInterceptor` obtains an [Authentication](../authentication/architecture.html#servlet-authentication-authentication) from the [SecurityContextHolder](../authentication/architecture.html#servlet-authentication-securitycontextholder).

* ![number 2](https://docs.spring.io/spring-security/reference/_images/icons/number_2.png) Second, `FilterSecurityInterceptor` creates a [`FilterInvocation`](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/web/FilterInvocation.html) from the `HttpServletRequest`, `HttpServletResponse`, and `FilterChain` that are passed into the `FilterSecurityInterceptor`.

* ![number 3](https://docs.spring.io/spring-security/reference/_images/icons/number_3.png) Next, it passes the `FilterInvocation` to `SecurityMetadataSource` to get the `ConfigAttribute`s.

* ![number 4](https://docs.spring.io/spring-security/reference/_images/icons/number_4.png) Finally, it passes the `Authentication`, `FilterInvocation`, and `ConfigAttribute`s to the xref:servlet/authorization.adoc#authz-access-decision-manager`AccessDecisionManager`.

  * ![number 5](https://docs.spring.io/spring-security/reference/_images/icons/number_5.png) If authorization is denied, an `AccessDeniedException` is thrown.
    In this case the [`ExceptionTranslationFilter`](../architecture.html#servlet-exceptiontranslationfilter) handles the `AccessDeniedException`.

  * ![number 6](https://docs.spring.io/spring-security/reference/_images/icons/number_6.png) If access is granted, `FilterSecurityInterceptor` continues with the [FilterChain](../architecture.html#servlet-filters-review) 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:

Example 1. Every Request Must be Authenticated

Java

```
protected void configure(HttpSecurity http) throws Exception {
	http
		// ...
		.authorizeRequests(authorize -> authorize
			.anyRequest().authenticated()
		);
}
```

XML

```
<http>
	<!-- ... -->
	<intercept-url pattern="/**" access="authenticated"/>
</http>
```

Kotlin

```
fun configure(http: HttpSecurity) {
    http {
        // ...
        authorizeRequests {
            authorize(anyRequest, authenticated)
        }
    }
}
```

We can configure Spring Security to have different rules by adding more rules in order of precedence.

Example 2. Authorize Requests

Java

```
protected void configure(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)
		);
}
```

XML

```
<http> (1)
	<!-- ... -->
	(2)
	<intercept-url pattern="/resources/**" access="permitAll"/>
	<intercept-url pattern="/signup" access="permitAll"/>
	<intercept-url pattern="/about" access="permitAll"/>

	<intercept-url pattern="/admin/**" access="hasRole('ADMIN')"/> (3)
	<intercept-url pattern="/db/**" access="hasRole('ADMIN') and hasRole('DBA')"/> (4)
	<intercept-url pattern="/**" access="denyAll"/> (5)
</http>
```

Kotlin

```
fun configure(http: HttpSecurity) {
   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)
        }
    }
}
```

|**1**|                                                  There are multiple authorization rules specified.<br/>Each rule is considered in the order they were declared.                                                  |
|-----|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|**2**|             We specified multiple URL patterns that any user can access.<br/>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".<br/>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".<br/>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.<br/>This is a good strategy if you do not want to accidentally forget to update your authorization rules.                     |

[Authorize HTTP Requests](authorize-http-requests.html)[Expression-Based Access Control](expression-based.html)