rsocket.adoc 14 KB

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