├── settings.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── test │ ├── resources │ │ ├── bootstrap.properties │ │ └── application-integration.properties │ └── java │ │ └── com │ │ └── livestreamchat │ │ └── pubsub │ │ ├── Auth0TestClient.java │ │ ├── RedisPubSubServiceTest.java │ │ └── PubSubControllerITests.java └── main │ ├── java │ └── com │ │ └── livestreamchat │ │ ├── pubsub │ │ ├── PubSubService.java │ │ ├── Message.java │ │ ├── config │ │ │ ├── RedisPubSubConfig.java │ │ │ └── RSocketSecurityConfig.java │ │ ├── PubSubController.java │ │ └── RedisPubSubService.java │ │ └── LivestreamChatApplication.java │ └── resources │ ├── application.properties │ └── META-INF │ └── additional-spring-configuration-metadata.json ├── README.md ├── .gitignore ├── gradlew.bat └── gradlew /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'livestream-chat' 2 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oli-broughton/livestream-chat/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/test/resources/bootstrap.properties: -------------------------------------------------------------------------------- 1 | embedded.redis.requirepass=false 2 | embedded.redis.host=localhost 3 | embedded.redis.port=6379 4 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.0.2-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # livestream-chat 2 | 3 | Horizontally scalable live stream chat. Built with Spring WebFlux, Redis PubSub, RSocket and Auth0. 4 | 5 | [Blog post](https://dev.to/olibroughton/building-a-scalable-live-stream-chat-service-with-spring-webflux-redis-pubsub-rsocket-and-auth0-22o9) 6 | -------------------------------------------------------------------------------- /src/main/java/com/livestreamchat/pubsub/PubSubService.java: -------------------------------------------------------------------------------- 1 | package com.livestreamchat.pubsub; 2 | 3 | import reactor.core.publisher.Flux; 4 | import reactor.core.publisher.Mono; 5 | 6 | public interface PubSubService { 7 | Mono publish(Message message); 8 | Flux subscribe(); 9 | } 10 | -------------------------------------------------------------------------------- /src/main/java/com/livestreamchat/pubsub/Message.java: -------------------------------------------------------------------------------- 1 | package com.livestreamchat.pubsub; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | @Data 8 | @AllArgsConstructor 9 | @NoArgsConstructor 10 | public class Message { 11 | String username; 12 | String message; 13 | } -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | # rsocket 2 | spring.rsocket.server.transport=websocket 3 | spring.rsocket.server.mapping-path=/rs 4 | 5 | # auth0 6 | spring.security.oauth2.resourceserver.jwt.issuer-uri=https://{YOUR_AUTH0_DOMAIN}.us.auth0.com/ 7 | auth0.audience={YOUR_AUTH0_API_AUDIENCE} 8 | auth0.username-claim={YOUR_AUTH0_USERNAME_CLAIM} -------------------------------------------------------------------------------- /src/main/java/com/livestreamchat/LivestreamChatApplication.java: -------------------------------------------------------------------------------- 1 | package com.livestreamchat; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import reactor.core.publisher.Hooks; 6 | 7 | @SpringBootApplication 8 | public class LivestreamChatApplication { 9 | public static void main(String[] args) { 10 | //https://github.com/rsocket/rsocket-java/issues/1018 11 | Hooks.onErrorDropped((throwable)->{}); 12 | SpringApplication.run(LivestreamChatApplication.class, args); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/**/build/ 6 | !**/src/test/**/build/ 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | bin/ 17 | !**/src/main/**/bin/ 18 | !**/src/test/**/bin/ 19 | 20 | ### IntelliJ IDEA ### 21 | .idea 22 | *.iws 23 | *.iml 24 | *.ipr 25 | out/ 26 | !**/src/main/**/out/ 27 | !**/src/test/**/out/ 28 | 29 | ### NetBeans ### 30 | /nbproject/private/ 31 | /nbbuild/ 32 | /dist/ 33 | /nbdist/ 34 | /.nb-gradle/ 35 | 36 | ### VS Code ### 37 | .vscode/ 38 | -------------------------------------------------------------------------------- /src/test/resources/application-integration.properties: -------------------------------------------------------------------------------- 1 | 2 | # auth0 dev domains 3 | spring.security.oauth2.resourceserver.jwt.issuer-uri={YOUR_AUTH0_DOMAIN} 4 | auth0.audience={YOUR_AUTH0_API_AUDIENCE} 5 | auth0.username-claim={YOUR_AUTH0_USERNAME_CLAIM} 6 | 7 | # auth0 test client 8 | auth0.test.client-id={YOUR_AUTH0_API_CLIENT_ID} 9 | auth0.test.client-secret={YOUR_AUTH0_API_CLIENT_SECRET} 10 | auth0.test.grant-type=password 11 | auth0.test.scope=read:current_user 12 | auth0.test.username={YOUR_AUTH0_API_TEST_USER_USERNAME} 13 | auth0.test.password={YOUR_AUTH0_API_TEST_USER_PASSWORD} 14 | auth0.test.expired-token={EXPIRED_ACCESS_TOKEN_FOR_TESTING} 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/additional-spring-configuration-metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "properties": [ 3 | { 4 | "name": "messaging.broadcastTopic", 5 | "type": "java.lang.String", 6 | "description": "Description for messaging.broadcastTopic." 7 | }, 8 | { 9 | "name": "jwt.secret", 10 | "type": "java.lang.String", 11 | "description": "Description for jwt.secret." 12 | }, 13 | { 14 | "name": "auth0.audience", 15 | "type": "java.lang.String", 16 | "description": "Description for auth0.audience." 17 | }, 18 | { 19 | "name": "auth0.username-claim", 20 | "type": "java.lang.String", 21 | "description": "Description for auth0.username-claim." 22 | } 23 | ] 24 | } -------------------------------------------------------------------------------- /src/main/java/com/livestreamchat/pubsub/config/RedisPubSubConfig.java: -------------------------------------------------------------------------------- 1 | package com.livestreamchat.pubsub.config; 2 | 3 | import com.livestreamchat.pubsub.Message; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory; 7 | import org.springframework.data.redis.core.ReactiveRedisTemplate; 8 | import org.springframework.data.redis.listener.ReactiveRedisMessageListenerContainer; 9 | import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 10 | import org.springframework.data.redis.serializer.RedisSerializationContext; 11 | import org.springframework.data.redis.serializer.StringRedisSerializer; 12 | 13 | @Configuration 14 | public class RedisPubSubConfig { 15 | 16 | @Bean 17 | public ReactiveRedisTemplate reactiveRedisTemplate(ReactiveRedisConnectionFactory factory) { 18 | 19 | StringRedisSerializer keySerializer = new StringRedisSerializer(); 20 | Jackson2JsonRedisSerializer valueSerializer = new Jackson2JsonRedisSerializer<>(Message.class); 21 | 22 | RedisSerializationContext.RedisSerializationContextBuilder builder = 23 | RedisSerializationContext.newSerializationContext(keySerializer); 24 | 25 | RedisSerializationContext context = 26 | builder.value(valueSerializer).build(); 27 | 28 | return new ReactiveRedisTemplate<>(factory, context); 29 | } 30 | 31 | @Bean 32 | ReactiveRedisMessageListenerContainer container(ReactiveRedisConnectionFactory factory) { 33 | return new ReactiveRedisMessageListenerContainer(factory); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/livestreamchat/pubsub/PubSubController.java: -------------------------------------------------------------------------------- 1 | package com.livestreamchat.pubsub; 2 | 3 | import lombok.extern.slf4j.Slf4j; 4 | import org.springframework.beans.factory.annotation.Value; 5 | import org.springframework.messaging.handler.annotation.MessageMapping; 6 | import org.springframework.messaging.rsocket.RSocketRequester; 7 | import org.springframework.messaging.rsocket.annotation.ConnectMapping; 8 | import org.springframework.security.core.annotation.AuthenticationPrincipal; 9 | import org.springframework.security.oauth2.jwt.Jwt; 10 | import org.springframework.stereotype.Controller; 11 | import reactor.core.publisher.Flux; 12 | import reactor.core.publisher.Mono; 13 | 14 | import java.util.Objects; 15 | 16 | @Controller 17 | @Slf4j 18 | public class PubSubController { 19 | 20 | @Value("${auth0.username-claim}") 21 | String usernameClaim; 22 | 23 | private final PubSubService messagingService; 24 | 25 | public PubSubController(PubSubService messagingService) { 26 | this.messagingService = messagingService; 27 | } 28 | 29 | @ConnectMapping 30 | void onConnect(RSocketRequester requester) { 31 | Objects.requireNonNull(requester.rsocket(), "rsocket should not be null") 32 | .onClose() 33 | .doOnError(error -> log.warn(requester.rsocketClient() + " Closed")) 34 | .doFinally(consumer -> log.info(requester.rsocketClient() + " Disconnected")) 35 | .subscribe(); 36 | } 37 | 38 | @MessageMapping("publish") 39 | Mono publish(String message, @AuthenticationPrincipal Mono token) { 40 | return token.map(jwt -> jwt.getClaimAsString(usernameClaim)) 41 | .flatMap(username -> messagingService.publish(new Message(username, message))); 42 | } 43 | 44 | @MessageMapping("subscribe") 45 | Flux subscribe() { 46 | return messagingService.subscribe(); 47 | } 48 | } -------------------------------------------------------------------------------- /src/main/java/com/livestreamchat/pubsub/RedisPubSubService.java: -------------------------------------------------------------------------------- 1 | package com.livestreamchat.pubsub; 2 | 3 | import org.springframework.data.redis.connection.ReactiveSubscription; 4 | import org.springframework.data.redis.core.ReactiveRedisTemplate; 5 | import org.springframework.data.redis.listener.ChannelTopic; 6 | import org.springframework.data.redis.listener.ReactiveRedisMessageListenerContainer; 7 | import org.springframework.stereotype.Service; 8 | import reactor.core.publisher.Flux; 9 | import reactor.core.publisher.Mono; 10 | 11 | import java.util.Collections; 12 | 13 | @Service 14 | public class RedisPubSubService implements PubSubService { 15 | 16 | private final ReactiveRedisTemplate reactiveTemplate; 17 | private final ReactiveRedisMessageListenerContainer reactiveMsgListenerContainer; 18 | 19 | private final ChannelTopic channelTopic = new ChannelTopic("broadcast"); 20 | 21 | public RedisPubSubService(ReactiveRedisTemplate reactiveTemplate, 22 | ReactiveRedisMessageListenerContainer reactiveMsgListenerContainer) { 23 | this.reactiveMsgListenerContainer = reactiveMsgListenerContainer; 24 | this.reactiveTemplate = reactiveTemplate; 25 | 26 | } 27 | 28 | @Override 29 | public Mono publish(Message message) { 30 | return this.reactiveTemplate 31 | .convertAndSend(channelTopic.getTopic(), message) 32 | .then(Mono.empty()); 33 | } 34 | 35 | @Override 36 | public Flux subscribe() { 37 | return reactiveMsgListenerContainer 38 | .receive(Collections.singletonList(channelTopic), 39 | reactiveTemplate.getSerializationContext().getKeySerializationPair(), 40 | reactiveTemplate.getSerializationContext().getValueSerializationPair()) 41 | .map(ReactiveSubscription.Message::getMessage); 42 | } 43 | } -------------------------------------------------------------------------------- /src/test/java/com/livestreamchat/pubsub/Auth0TestClient.java: -------------------------------------------------------------------------------- 1 | package com.livestreamchat.pubsub; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | import org.springframework.beans.factory.annotation.Value; 6 | import org.springframework.boot.context.properties.ConfigurationProperties; 7 | import org.springframework.boot.test.context.TestConfiguration; 8 | import org.springframework.core.ParameterizedTypeReference; 9 | import org.springframework.http.MediaType; 10 | import org.springframework.test.context.ActiveProfiles; 11 | import org.springframework.web.reactive.function.BodyInserters; 12 | import org.springframework.web.reactive.function.client.WebClient; 13 | import reactor.core.publisher.Mono; 14 | 15 | import java.util.Map; 16 | 17 | @ActiveProfiles("integration") 18 | @TestConfiguration 19 | @ConfigurationProperties(prefix = "auth0.test") 20 | @Setter 21 | @Getter 22 | // integration tests use this auth0 flow for retrieving a valid access token : https://auth0.com/docs/flows/resource-owner-password-flow 23 | public class Auth0TestClient { 24 | 25 | @Value("${auth0.audience}") 26 | String audience; 27 | @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}") 28 | String domainUri; 29 | 30 | private String clientId; 31 | private String clientSecret; 32 | private String grantType; 33 | private String scope; 34 | private String username; 35 | private String password; 36 | private String expiredToken; 37 | 38 | Mono requestValidAccessToken(){ 39 | return WebClient.builder() 40 | .baseUrl(domainUri) 41 | .build() 42 | .post() 43 | .uri("/oauth/token") 44 | .contentType(MediaType.APPLICATION_FORM_URLENCODED) 45 | .body(BodyInserters 46 | .fromFormData("grant_type", grantType) 47 | .with("username", username) 48 | .with("password", password) 49 | .with("audience", audience) 50 | .with("scope", scope) 51 | .with("client_id", clientId) 52 | .with("client_secret", clientSecret) 53 | ).retrieve() 54 | .bodyToMono(new ParameterizedTypeReference>() { 55 | }) 56 | .map(map -> map.get("access_token")); 57 | } 58 | 59 | Mono requestExpiredAccessToken(){ 60 | return Mono.just(expiredToken); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/test/java/com/livestreamchat/pubsub/RedisPubSubServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.livestreamchat.pubsub; 2 | 3 | import org.junit.jupiter.api.BeforeEach; 4 | import org.junit.jupiter.api.Test; 5 | import org.junit.jupiter.api.extension.ExtendWith; 6 | import org.mockito.Answers; 7 | import org.mockito.ArgumentMatchers; 8 | import org.mockito.Mock; 9 | import org.mockito.Mockito; 10 | import org.mockito.junit.jupiter.MockitoExtension; 11 | import org.springframework.data.redis.connection.ReactiveSubscription; 12 | import org.springframework.data.redis.core.ReactiveRedisTemplate; 13 | import org.springframework.data.redis.listener.ChannelTopic; 14 | import org.springframework.data.redis.listener.ReactiveRedisMessageListenerContainer; 15 | import org.springframework.data.redis.serializer.RedisSerializationContext; 16 | import reactor.core.publisher.Flux; 17 | import reactor.core.publisher.Mono; 18 | import reactor.test.StepVerifier; 19 | 20 | @ExtendWith(MockitoExtension.class) 21 | class RedisPubSubServiceTest { 22 | 23 | @Mock(answer = Answers.RETURNS_DEEP_STUBS) 24 | private ReactiveRedisTemplate reactiveRedisTemplate; 25 | 26 | @Mock(answer = Answers.RETURNS_DEEP_STUBS) 27 | private ReactiveRedisMessageListenerContainer reactiveRedisMessageListenerContainer; 28 | 29 | @Mock 30 | private RedisSerializationContext.SerializationPair stringSerializationPair; 31 | 32 | @Mock 33 | private RedisSerializationContext.SerializationPair messageSerializationPair; 34 | 35 | private PubSubService messagingService; 36 | 37 | @BeforeEach 38 | void setup(){ 39 | messagingService = new RedisPubSubService(reactiveRedisTemplate, reactiveRedisMessageListenerContainer); 40 | } 41 | 42 | @Test 43 | void send() { 44 | var sendChannel = "broadcast"; 45 | var testMessage = new Message("testuser", "test message"); 46 | 47 | Mockito.when(reactiveRedisTemplate.convertAndSend( 48 | ArgumentMatchers.eq(sendChannel), 49 | ArgumentMatchers.eq(testMessage))).thenReturn(Mono.just(1L)); 50 | 51 | StepVerifier.create(messagingService.publish(testMessage)).verifyComplete(); 52 | } 53 | 54 | @Test 55 | void receive() { 56 | 57 | Mockito.when(reactiveRedisTemplate.getSerializationContext().getKeySerializationPair()).thenReturn(stringSerializationPair); 58 | Mockito.when(reactiveRedisTemplate.getSerializationContext().getValueSerializationPair()).thenReturn(messageSerializationPair); 59 | 60 | var testMessage = new Message("testuser", "test message"); 61 | 62 | Mockito.when(reactiveRedisMessageListenerContainer.receive( 63 | ArgumentMatchers.>any(), 64 | ArgumentMatchers.eq(stringSerializationPair), 65 | ArgumentMatchers.eq(messageSerializationPair)) 66 | ).thenReturn(Flux.just(new ReactiveSubscription.ChannelMessage<>("broadcast", testMessage))); 67 | 68 | var messages = messagingService.subscribe(); 69 | 70 | StepVerifier.create(messages).expectNext(testMessage).thenCancel().verify(); 71 | } 72 | } -------------------------------------------------------------------------------- /src/main/java/com/livestreamchat/pubsub/config/RSocketSecurityConfig.java: -------------------------------------------------------------------------------- 1 | package com.livestreamchat.pubsub.config; 2 | 3 | import org.springframework.beans.factory.annotation.Value; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.messaging.rsocket.RSocketStrategies; 7 | import org.springframework.messaging.rsocket.annotation.support.RSocketMessageHandler; 8 | import org.springframework.security.config.Customizer; 9 | import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; 10 | import org.springframework.security.config.annotation.rsocket.EnableRSocketSecurity; 11 | import org.springframework.security.config.annotation.rsocket.RSocketSecurity; 12 | import org.springframework.security.messaging.handler.invocation.reactive.AuthenticationPrincipalArgumentResolver; 13 | import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator; 14 | import org.springframework.security.oauth2.core.OAuth2Error; 15 | import org.springframework.security.oauth2.core.OAuth2TokenValidator; 16 | import org.springframework.security.oauth2.core.OAuth2TokenValidatorResult; 17 | import org.springframework.security.oauth2.jwt.*; 18 | import org.springframework.security.rsocket.core.PayloadSocketAcceptorInterceptor; 19 | import org.springframework.web.util.pattern.PathPatternRouteMatcher; 20 | 21 | @Configuration 22 | @EnableRSocketSecurity 23 | @EnableReactiveMethodSecurity 24 | public class RSocketSecurityConfig { 25 | 26 | @Value("${auth0.audience}") 27 | String audience; 28 | @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}") 29 | String issuer; 30 | @Value("${auth0.username-claim}") 31 | String usernameClaim; 32 | 33 | @Bean 34 | public PayloadSocketAcceptorInterceptor rsocketInterceptor(RSocketSecurity rSocketSecurity) { 35 | return rSocketSecurity.authorizePayload(authorize -> 36 | authorize.route("publish").authenticated() 37 | .anyExchange().permitAll() 38 | ) 39 | .jwt(Customizer.withDefaults()) 40 | .build(); 41 | } 42 | 43 | @Bean 44 | public ReactiveJwtDecoder reactiveJwtDecoder() { 45 | 46 | var reactiveJwtDecoder = (NimbusReactiveJwtDecoder) ReactiveJwtDecoders.fromOidcIssuerLocation(issuer); 47 | 48 | OAuth2TokenValidator audienceValidator = (jwt) -> { 49 | OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null); 50 | if (jwt.getAudience().contains(audience)) { 51 | return OAuth2TokenValidatorResult.success(); 52 | } 53 | return OAuth2TokenValidatorResult.failure(error); 54 | }; 55 | 56 | OAuth2TokenValidator usernameValidator = (jwt) -> { 57 | OAuth2Error error = new OAuth2Error("invalid_token", "The required username is missing", null); 58 | if (jwt.getClaimAsString(usernameClaim) != null) { 59 | return OAuth2TokenValidatorResult.success(); 60 | } 61 | return OAuth2TokenValidatorResult.failure(error); 62 | }; 63 | 64 | OAuth2TokenValidator withIssuer = JwtValidators.createDefaultWithIssuer(issuer); 65 | OAuth2TokenValidator compositeValidator = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator, usernameValidator); 66 | 67 | reactiveJwtDecoder.setJwtValidator(compositeValidator); 68 | 69 | return reactiveJwtDecoder; 70 | } 71 | 72 | @Bean 73 | RSocketMessageHandler messageHandler(RSocketStrategies strategies) { 74 | RSocketMessageHandler mh = new RSocketMessageHandler(); 75 | mh.getArgumentResolverConfigurer().addCustomResolver( 76 | new AuthenticationPrincipalArgumentResolver()); 77 | mh.setRouteMatcher(new PathPatternRouteMatcher()); 78 | mh.setRSocketStrategies(strategies); 79 | return mh; 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/test/java/com/livestreamchat/pubsub/PubSubControllerITests.java: -------------------------------------------------------------------------------- 1 | package com.livestreamchat.pubsub; 2 | 3 | import io.rsocket.exceptions.ApplicationErrorException; 4 | import org.junit.jupiter.api.*; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.messaging.rsocket.RSocketRequester; 9 | import org.springframework.security.rsocket.metadata.BearerTokenMetadata; 10 | import org.springframework.test.context.ActiveProfiles; 11 | import reactor.core.publisher.Hooks; 12 | import reactor.test.StepVerifier; 13 | 14 | import java.net.URI; 15 | import java.time.Duration; 16 | 17 | @ActiveProfiles("integration") 18 | @TestInstance(TestInstance.Lifecycle.PER_CLASS) 19 | @EnableConfigurationProperties(value = Auth0TestClient.class) 20 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) 21 | class PubSubControllerITests { 22 | @Autowired 23 | Auth0TestClient auth0TestClient; 24 | 25 | private static RSocketRequester requester; 26 | 27 | @BeforeAll 28 | public void setupUp(@Autowired RSocketRequester.Builder builder) { 29 | 30 | //Hide cancellation exception from test log https://github.com/rsocket/rsocket-java/issues/1018 31 | Hooks.onErrorDropped((throwable) -> { 32 | }); 33 | requester = builder.websocket(URI.create("ws://localhost:8080/rs")); 34 | } 35 | 36 | @AfterAll 37 | public static void tearDown() { 38 | requester.dispose(); 39 | } 40 | 41 | @Test 42 | void requestValidToken(){ 43 | var accessTokenRequest = auth0TestClient.requestValidAccessToken(); 44 | StepVerifier.create(accessTokenRequest). 45 | consumeNextWith(accessToken->Assertions.assertFalse(accessToken.isEmpty()) ) 46 | .verifyComplete(); 47 | } 48 | 49 | @Test 50 | void sendMessage() { 51 | var publishRoute = "publish"; 52 | var testMessage = "test message"; 53 | 54 | var request = auth0TestClient.requestValidAccessToken() 55 | .flatMap(token -> requester. 56 | route(publishRoute) 57 | .metadata(token, BearerTokenMetadata.BEARER_AUTHENTICATION_MIME_TYPE) 58 | .data(testMessage) 59 | .retrieveMono(Void.class)); 60 | 61 | StepVerifier.create(request).verifyComplete(); 62 | } 63 | 64 | @Test 65 | void sendMessageExpiredToken() { 66 | var publishRoute = "publish"; 67 | var testMessage = "test message"; 68 | 69 | var response = auth0TestClient.requestExpiredAccessToken() 70 | .flatMap(token -> requester. 71 | route(publishRoute) 72 | .metadata(token, BearerTokenMetadata.BEARER_AUTHENTICATION_MIME_TYPE) 73 | .data(testMessage) 74 | .retrieveMono(Void.class)); 75 | 76 | StepVerifier.create(response) 77 | .expectError(ApplicationErrorException.class) 78 | .verify(Duration.ofSeconds(1)); 79 | } 80 | 81 | @Test 82 | void receiveMessage() { 83 | var publishRoute = "publish"; 84 | var subscribeRoute = "subscribe"; 85 | var testMessage = "test message"; 86 | 87 | var receivedMessages = requester 88 | .route(subscribeRoute) 89 | .retrieveFlux(Message.class) 90 | .cache(); 91 | 92 | auth0TestClient.requestValidAccessToken() 93 | .flatMap(token -> requester. 94 | route(publishRoute) 95 | .metadata(token, BearerTokenMetadata.BEARER_AUTHENTICATION_MIME_TYPE) 96 | .data(testMessage) 97 | .retrieveMono(Void.class)) 98 | .subscribe(); 99 | 100 | StepVerifier.create(receivedMessages) 101 | .expectNext(new Message(auth0TestClient.getUsername(), testMessage)) 102 | .thenCancel() 103 | .verify(Duration.ofSeconds(1)); 104 | 105 | } 106 | } -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | --------------------------------------------------------------------------------