rsocket.adoc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. [[rsocket]]
  2. = RSocket Security
  3. Spring Security's RSocket support relies on a `SocketAcceptorInterceptor`.
  4. The main entry point into security is in `PayloadSocketAcceptorInterceptor`, which adapts the RSocket APIs to allow intercepting a `PayloadExchange` with `PayloadInterceptor` implementations.
  5. The following example shows a minimal RSocket Security configuration:
  6. * Hello RSocket {gh-samples-url}/reactive/rsocket/hello-security[hellorsocket]
  7. * https://github.com/rwinch/spring-flights/tree/security[Spring Flights]
  8. == Minimal RSocket Security Configuration
  9. You can find a minimal RSocket Security configuration below:
  10. ====
  11. .Java
  12. [source,java,role="primary"]
  13. ----
  14. @Configuration
  15. @EnableRSocketSecurity
  16. public class HelloRSocketSecurityConfig {
  17. @Bean
  18. public MapReactiveUserDetailsService userDetailsService() {
  19. UserDetails user = User.withDefaultPasswordEncoder()
  20. .username("user")
  21. .password("user")
  22. .roles("USER")
  23. .build();
  24. return new MapReactiveUserDetailsService(user);
  25. }
  26. }
  27. ----
  28. .Kotlin
  29. [source,kotlin,role="secondary"]
  30. ----
  31. @Configuration
  32. @EnableRSocketSecurity
  33. open class HelloRSocketSecurityConfig {
  34. @Bean
  35. open fun userDetailsService(): MapReactiveUserDetailsService {
  36. val user = User.withDefaultPasswordEncoder()
  37. .username("user")
  38. .password("user")
  39. .roles("USER")
  40. .build()
  41. return MapReactiveUserDetailsService(user)
  42. }
  43. }
  44. ----
  45. ====
  46. This configuration enables <<rsocket-authentication-simple,simple authentication>> and sets up <<rsocket-authorization,rsocket-authorization>> to require an authenticated user for any request.
  47. == Adding SecuritySocketAcceptorInterceptor
  48. For Spring Security to work, we need to apply `SecuritySocketAcceptorInterceptor` to the `ServerRSocketFactory`.
  49. Doing so connects our `PayloadSocketAcceptorInterceptor` with the RSocket infrastructure.
  50. In a Spring Boot application, you can do this automatically by using `RSocketSecurityAutoConfiguration` with the following code:
  51. ====
  52. [source,java]
  53. ----
  54. @Bean
  55. RSocketServerCustomizer springSecurityRSocketSecurity(SecuritySocketAcceptorInterceptor interceptor) {
  56. return (server) -> server.interceptors((registry) -> registry.forSocketAcceptor(interceptor));
  57. }
  58. ----
  59. ====
  60. [[rsocket-authentication]]
  61. == RSocket Authentication
  62. RSocket authentication is performed with `AuthenticationPayloadInterceptor`, which acts as a controller to invoke a `ReactiveAuthenticationManager` instance.
  63. [[rsocket-authentication-setup-vs-request]]
  64. === Authentication at Setup versus Request Time
  65. Generally, authentication can occur at setup time or at request time or both.
  66. Authentication at setup time makes sense in a few scenarios.
  67. A common scenarios is when a single user (such as a mobile connection) uses an RSocket connection.
  68. In this case, only a single user uses the connection, so authentication can be done once at connection time.
  69. In a scenario where the RSocket connection is shared, it makes sense to send credentials on each request.
  70. For example, a web application that connects to an RSocket server as a downstream service would make a single connection that all users use.
  71. In this case, if the RSocket server needs to perform authorization based on the web application's users credentials, authentication for each request makes sense.
  72. In some scenarios, authentication at both setup and for each request makes sense.
  73. Consider a web application, as described previously.
  74. If we need to restrict the connection to the web application itself, we can provide a credential with a `SETUP` authority at connection time.
  75. Then each user can have different authorities but not the `SETUP` authority.
  76. This means that individual users can make requests but not make additional connections.
  77. [[rsocket-authentication-simple]]
  78. === Simple Authentication
  79. Spring Security has support for the https://github.com/rsocket/rsocket/blob/5920ed374d008abb712cb1fd7c9d91778b2f4a68/Extensions/Security/Simple.md[Simple Authentication Metadata Extension].
  80. [NOTE]
  81. ====
  82. Basic Authentication evolved into Simple Authentication and is only supported for backward compatibility.
  83. See `RSocketSecurity.basicAuthentication(Customizer)` for setting it up.
  84. ====
  85. The RSocket receiver can decode the credentials by using `AuthenticationPayloadExchangeConverter`, which is automatically setup by using the `simpleAuthentication` portion of the DSL.
  86. The following example shows an explicit configuration:
  87. ====
  88. .Java
  89. [source,java,role="primary"]
  90. ----
  91. @Bean
  92. PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
  93. rsocket
  94. .authorizePayload(authorize ->
  95. authorize
  96. .anyRequest().authenticated()
  97. .anyExchange().permitAll()
  98. )
  99. .simpleAuthentication(Customizer.withDefaults());
  100. return rsocket.build();
  101. }
  102. ----
  103. .Kotlin
  104. [source,kotlin,role="secondary"]
  105. ----
  106. @Bean
  107. open fun rsocketInterceptor(rsocket: RSocketSecurity): PayloadSocketAcceptorInterceptor {
  108. rsocket
  109. .authorizePayload { authorize -> authorize
  110. .anyRequest().authenticated()
  111. .anyExchange().permitAll()
  112. }
  113. .simpleAuthentication(withDefaults())
  114. return rsocket.build()
  115. }
  116. ----
  117. ====
  118. The RSocket sender can send credentials by using `SimpleAuthenticationEncoder`, which you can add to Spring's `RSocketStrategies`.
  119. ====
  120. .Java
  121. [source,java,role="primary"]
  122. ----
  123. RSocketStrategies.Builder strategies = ...;
  124. strategies.encoder(new SimpleAuthenticationEncoder());
  125. ----
  126. .Kotlin
  127. [source,kotlin,role="secondary"]
  128. ----
  129. var strategies: RSocketStrategies.Builder = ...
  130. strategies.encoder(SimpleAuthenticationEncoder())
  131. ----
  132. ====
  133. You can then use it to send a username and password to the receiver in the setup:
  134. ====
  135. .Java
  136. [source,java,role="primary"]
  137. ----
  138. MimeType authenticationMimeType =
  139. MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());
  140. UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
  141. Mono<RSocketRequester> requester = RSocketRequester.builder()
  142. .setupMetadata(credentials, authenticationMimeType)
  143. .rsocketStrategies(strategies.build())
  144. .connectTcp(host, port);
  145. ----
  146. .Kotlin
  147. [source,kotlin,role="secondary"]
  148. ----
  149. val authenticationMimeType: MimeType =
  150. MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.string)
  151. val credentials = UsernamePasswordMetadata("user", "password")
  152. val requester: Mono<RSocketRequester> = RSocketRequester.builder()
  153. .setupMetadata(credentials, authenticationMimeType)
  154. .rsocketStrategies(strategies.build())
  155. .connectTcp(host, port)
  156. ----
  157. ====
  158. Alternatively or additionally, a username and password can be sent in a request.
  159. ====
  160. .Java
  161. [source,java,role="primary"]
  162. ----
  163. Mono<RSocketRequester> requester;
  164. UsernamePasswordMetadata credentials = new UsernamePasswordMetadata("user", "password");
  165. public Mono<AirportLocation> findRadar(String code) {
  166. return this.requester.flatMap(req ->
  167. req.route("find.radar.{code}", code)
  168. .metadata(credentials, authenticationMimeType)
  169. .retrieveMono(AirportLocation.class)
  170. );
  171. }
  172. ----
  173. .Kotlin
  174. [source,kotlin,role="secondary"]
  175. ----
  176. import org.springframework.messaging.rsocket.retrieveMono
  177. // ...
  178. var requester: Mono<RSocketRequester>? = null
  179. var credentials = UsernamePasswordMetadata("user", "password")
  180. open fun findRadar(code: String): Mono<AirportLocation> {
  181. return requester!!.flatMap { req ->
  182. req.route("find.radar.{code}", code)
  183. .metadata(credentials, authenticationMimeType)
  184. .retrieveMono<AirportLocation>()
  185. }
  186. }
  187. ----
  188. ====
  189. [[rsocket-authentication-jwt]]
  190. === JWT
  191. Spring Security has support for the https://github.com/rsocket/rsocket/blob/5920ed374d008abb712cb1fd7c9d91778b2f4a68/Extensions/Security/Bearer.md[Bearer Token Authentication Metadata Extension].
  192. The support comes in the form of authenticating a JWT (determining that the JWT is valid) and then using the JWT to make authorization decisions.
  193. The RSocket receiver can decode the credentials by using `BearerPayloadExchangeConverter`, which is automatically setup by using the `jwt` portion of the DSL.
  194. The following listing shows an example configuration:
  195. ====
  196. .Java
  197. [source,java,role="primary"]
  198. ----
  199. @Bean
  200. PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rsocket) {
  201. rsocket
  202. .authorizePayload(authorize ->
  203. authorize
  204. .anyRequest().authenticated()
  205. .anyExchange().permitAll()
  206. )
  207. .jwt(Customizer.withDefaults());
  208. return rsocket.build();
  209. }
  210. ----
  211. .Kotlin
  212. [source,kotlin,role="secondary"]
  213. ----
  214. @Bean
  215. fun rsocketInterceptor(rsocket: RSocketSecurity): PayloadSocketAcceptorInterceptor {
  216. rsocket
  217. .authorizePayload { authorize -> authorize
  218. .anyRequest().authenticated()
  219. .anyExchange().permitAll()
  220. }
  221. .jwt(withDefaults())
  222. return rsocket.build()
  223. }
  224. ----
  225. ====
  226. The configuration above relies on the existence of a `ReactiveJwtDecoder` `@Bean` being present.
  227. An example of creating one from the issuer can be found below:
  228. ====
  229. .Java
  230. [source,java,role="primary"]
  231. ----
  232. @Bean
  233. ReactiveJwtDecoder jwtDecoder() {
  234. return ReactiveJwtDecoders
  235. .fromIssuerLocation("https://example.com/auth/realms/demo");
  236. }
  237. ----
  238. .Kotlin
  239. [source,kotlin,role="secondary"]
  240. ----
  241. @Bean
  242. fun jwtDecoder(): ReactiveJwtDecoder {
  243. return ReactiveJwtDecoders
  244. .fromIssuerLocation("https://example.com/auth/realms/demo")
  245. }
  246. ----
  247. ====
  248. The RSocket sender does not need to do anything special to send the token, because the value is a simple `String`.
  249. The following example sends the token at setup time:
  250. ====
  251. .Java
  252. [source,java,role="primary"]
  253. ----
  254. MimeType authenticationMimeType =
  255. MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());
  256. BearerTokenMetadata token = ...;
  257. Mono<RSocketRequester> requester = RSocketRequester.builder()
  258. .setupMetadata(token, authenticationMimeType)
  259. .connectTcp(host, port);
  260. ----
  261. .Kotlin
  262. [source,kotlin,role="secondary"]
  263. ----
  264. val authenticationMimeType: MimeType =
  265. MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.string)
  266. val token: BearerTokenMetadata = ...
  267. val requester = RSocketRequester.builder()
  268. .setupMetadata(token, authenticationMimeType)
  269. .connectTcp(host, port)
  270. ----
  271. ====
  272. Alternatively or additionally, you can send the token in a request:
  273. ====
  274. .Java
  275. [source,java,role="primary"]
  276. ----
  277. MimeType authenticationMimeType =
  278. MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.getString());
  279. Mono<RSocketRequester> requester;
  280. BearerTokenMetadata token = ...;
  281. public Mono<AirportLocation> findRadar(String code) {
  282. return this.requester.flatMap(req ->
  283. req.route("find.radar.{code}", code)
  284. .metadata(token, authenticationMimeType)
  285. .retrieveMono(AirportLocation.class)
  286. );
  287. }
  288. ----
  289. .Kotlin
  290. [source,kotlin,role="secondary"]
  291. ----
  292. val authenticationMimeType: MimeType =
  293. MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_AUTHENTICATION.string)
  294. var requester: Mono<RSocketRequester>? = null
  295. val token: BearerTokenMetadata = ...
  296. open fun findRadar(code: String): Mono<AirportLocation> {
  297. return this.requester!!.flatMap { req ->
  298. req.route("find.radar.{code}", code)
  299. .metadata(token, authenticationMimeType)
  300. .retrieveMono<AirportLocation>()
  301. }
  302. }
  303. ----
  304. ====
  305. [[rsocket-authorization]]
  306. == RSocket Authorization
  307. RSocket authorization is performed with `AuthorizationPayloadInterceptor`, which acts as a controller to invoke a `ReactiveAuthorizationManager` instance.
  308. You can use the DSL to set up authorization rules based upon the `PayloadExchange`.
  309. The following listing shows an example configuration:
  310. ====
  311. .Java
  312. [source,java,role="primary"]
  313. ----
  314. rsocket
  315. .authorizePayload(authz ->
  316. authz
  317. .setup().hasRole("SETUP") // <1>
  318. .route("fetch.profile.me").authenticated() // <2>
  319. .matcher(payloadExchange -> isMatch(payloadExchange)) // <3>
  320. .hasRole("CUSTOM")
  321. .route("fetch.profile.{username}") // <4>
  322. .access((authentication, context) -> checkFriends(authentication, context))
  323. .anyRequest().authenticated() // <5>
  324. .anyExchange().permitAll() // <6>
  325. );
  326. ----
  327. .Kotlin
  328. [source,kotlin,role="secondary"]
  329. ----
  330. rsocket
  331. .authorizePayload { authz ->
  332. authz
  333. .setup().hasRole("SETUP") // <1>
  334. .route("fetch.profile.me").authenticated() // <2>
  335. .matcher { payloadExchange -> isMatch(payloadExchange) } // <3>
  336. .hasRole("CUSTOM")
  337. .route("fetch.profile.{username}") // <4>
  338. .access { authentication, context -> checkFriends(authentication, context) }
  339. .anyRequest().authenticated() // <5>
  340. .anyExchange().permitAll()
  341. } // <6>
  342. ----
  343. <1> Setting up a connection requires the `ROLE_SETUP` authority.
  344. <2> If the route is `fetch.profile.me`, authorization only requires the user to be authenticated.
  345. <3> In this rule, we set up a custom matcher, where authorization requires the user to have the `ROLE_CUSTOM` authority.
  346. <4> This rule uses custom authorization.
  347. The matcher expresses a variable with a name of `username` that is made available in the `context`.
  348. A custom authorization rule is exposed in the `checkFriends` method.
  349. <5> This rule ensures that a request that does not already have a rule requires the user to be authenticated.
  350. A request is where the metadata is included.
  351. It would not include additional payloads.
  352. <6> This rule ensures that any exchange that does not already have a rule is allowed for anyone.
  353. In this example, it means that payloads that have no metadata also have no authorization rules.
  354. ====
  355. Note that authorization rules are performed in order.
  356. Only the first authorization rule that matches is invoked.