Add authorizeRequests() example

This commit is contained in:
Dave Syer
2025-01-24 13:04:53 +00:00
parent be643c3627
commit 3ac7569d5c

View File

@@ -214,4 +214,25 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
By default CSRF protection is automatically disabled for gRPC requests because it is incompatible with the protocol.
You can switch off that behaviour and configure your own CSRF protection if you want to by explicitly setting `spring.grpc.security.csrf.enabled=true`.
A servlet application that exposes gRPC endpoints on a different port (with `spring.grpc.server.servlet.enabled=false`) will also not have CSRF protection disabled by default.
A servlet application that exposes gRPC endpoints on a different port (with `spring.grpc.server.servlet.enabled=false`) will also not have CSRF protection disabled by default.
=== Securing Individual Methods
Individual gRPC methods can be secured by adding `@PreAuthorize` to the method definition.
Or you can use the knowledge that the HTTP endpoint is `<service>/<method>` to configure the security using the usual `HttpSecurity` configuration.
Example:
[source,java]
----
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests((requests) -> requests
.requestMatchers("/Simple/SayHello").hasRole("USER")
.requestMatchers("/Simple/StreamHello").hasRole("ADMIN")
.requestMatchers("/grpc.*/*").permitAll()
.anyRequest().authenticated())
.build();
}
----
Here we allow access to the `Simple/SayHello` method to users with the `USER` role, and to the `Simple/StreamHello` method to users with the `ADMIN` role, and allow access to all gRPC-provided services (like reflection and health indicators), while disallowing access to all other methods unless authenticated.