rsocket.adoc 14 KB

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