rsocket.adoc 14 KB

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