2
0

rsocket.adoc 13 KB

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