Skip to content

Commit b28ed3d

Browse files
author
Dave Syer
committed
Add authorizeRequests() example
1 parent be643c3 commit b28ed3d

File tree

1 file changed

+22
-1
lines changed
  • spring-grpc-docs/src/main/antora/modules/ROOT/pages

1 file changed

+22
-1
lines changed

spring-grpc-docs/src/main/antora/modules/ROOT/pages/server.adoc

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -214,4 +214,25 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
214214

215215
By default CSRF protection is automatically disabled for gRPC requests because it is incompatible with the protocol.
216216
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`.
217-
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.
217+
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.
218+
219+
=== Securing Individual Methods
220+
221+
Individual gRPC methods can be secured by adding `@PreAuthorize` to the method definition.
222+
Or you can use the knowledge that the HTTP endpoint is `<service>/<method>` to configure the security using the usual `HttpSecurity` configuration.
223+
Example:
224+
225+
[source,java]
226+
----
227+
@Bean
228+
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
229+
return http.authorizeHttpRequests((requests) -> requests
230+
.requestMatchers("/Simple/SayHello").hasRole("USER")
231+
.requestMatchers("/Simple/StreamHello").hasRole("ADMIN")
232+
.requestMatchers("/grpc.*/*").permitAll()
233+
.anyRequest().authenticated())
234+
.build();
235+
}
236+
----
237+
238+
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 services (like reflection and health indicators), while disallowing access to all other methods unless authenticated.

0 commit comments

Comments
 (0)