Browse Source

add simple ws message handler

cloud-keycloak
Dmitriy Sim 3 years ago
parent
commit
1139298609
5 changed files with 67 additions and 30 deletions
  1. +31
    -29
      demo-client-app/src/App.js
  2. +1
    -0
      demo-resource-server/build.gradle
  3. +2
    -1
      demo-resource-server/src/main/java/ru/digitalbanana/demoresourceserver/config/WebSocketConfig.java
  4. +32
    -0
      demo-resource-server/src/main/java/ru/digitalbanana/demoresourceserver/websocket/controller/SimpleController.java
  5. +1
    -0
      demo-resource-server/src/main/resources/application.yml

+ 31
- 29
demo-client-app/src/App.js View File

@ -4,53 +4,55 @@ import SockJS from "sockjs-client";
import logo from "./logo.svg";
import "./App.css";
let stomp
let stomp;
const connect = async (token) => {
if (stomp != null) return;
console.info("Connect to Websocket");
const sock = new SockJS("/api/ws");
const sock = new SockJS("http://localhost:8081/api/ws");
stomp = Stomp.over(sock);
stomp.debug = (msg) => {}
stomp.connect(
{"X-Authorization": token},
{ "X-Authorization": token },
(frame) => {
console.log("Connected", frame);
const requestUrl = "/app/simple";
let params = {
tratata: 1,
gratata: 0
}
stomp.send(
requestUrl,
JSON.stringify(params)
);
stomp.subscribe("/user/simple", (results, errors)=>{
console.log("results: ", results);
console.log("errors: ", errors);
gratata: 0,
};
stomp.subscribe("/user/simple", (results) => {
console.log(`msg from server: ${results.body}`);
});
stomp.send(requestUrl, JSON.stringify(params));
},
error => {
(error) => {
console.error("Disconnected: ", error);
}
},
);
}
};
function App({ keycloak }) {
const fetchFromApi = useCallback(async (url) => {
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${keycloak.token}`,
},
});
if (response.ok) {
alert(await response.text());
} else {
console.error(response.statusText);
}
}, [keycloak.token]);
const fetchFromApi = useCallback(
async (url) => {
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${keycloak.token}`,
},
});
if (response.ok) {
alert(await response.text());
} else {
console.error(response.statusText);
}
},
[keycloak.token],
);
useEffect(() => {
connect(keycloak.token);
@ -67,7 +69,7 @@ function App({ keycloak }) {
className="App-link"
onClick={(e) => {
e.preventDefault();
fetchFromApi("/api/userinfo");
fetchFromApi("http://localhost:8081/api/userinfo");
}}
>
Get user email
@ -77,7 +79,7 @@ function App({ keycloak }) {
className="App-link"
onClick={(e) => {
e.preventDefault();
fetchFromApi("/api/users");
fetchFromApi("http://localhost:8081/api/users");
}}
>
Get all users


+ 1
- 0
demo-resource-server/build.gradle View File

@ -23,6 +23,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-websocket'
implementation 'org.springframework.security:spring-security-messaging'
runtimeOnly 'org.postgresql:postgresql'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
testImplementation 'org.springframework.boot:spring-boot-starter-test'


+ 2
- 1
demo-resource-server/src/main/java/ru/digitalbanana/demoresourceserver/config/WebSocketConfig.java View File

@ -41,7 +41,7 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
if (StompCommand.CONNECT.equals(accessor.getCommand())) {
List<String> authorization = accessor.getNativeHeader("X-Authorization");
String accessToken = authorization.get(0);//.split(" ")[1];
String accessToken = authorization.get(0);
Jwt jwt = jwtDecoder.decode(accessToken);
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
Authentication authentication = converter.convert(jwt);
@ -54,6 +54,7 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/simple");
registry.setApplicationDestinationPrefixes("/app");
}


+ 32
- 0
demo-resource-server/src/main/java/ru/digitalbanana/demoresourceserver/websocket/controller/SimpleController.java View File

@ -0,0 +1,32 @@
package ru.digitalbanana.demoresourceserver.websocket.controller;
import java.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import lombok.extern.slf4j.Slf4j;
@Controller
@Slf4j
public class SimpleController {
@Autowired
private SimpMessageSendingOperations messaging;
@MessageMapping("/simple")
public void simple(@AuthenticationPrincipal Principal principal) {
String userId = principal.getName();
log.info("Received simple message from {}", userId);
messaging.convertAndSendToUser(
userId,
"/simple",
"Hello, my friend!!!!!"
);
}
}

+ 1
- 0
demo-resource-server/src/main/resources/application.yml View File

@ -4,6 +4,7 @@ server:
context-path: /api
forward-headers-strategy: framework # nginx reverse proxy
logging.level:
'[ru.digitalbanana.demoresourceserver]': info
'[org.springframework.web]': debug
####### resource server configuration properties
spring:


Loading…
Cancel
Save