|
15 | 15 | */ |
16 | 16 | package com.greglturnquist.learningspringboot.chat; |
17 | 17 |
|
18 | | -import java.util.HashMap; |
19 | | -import java.util.Map; |
20 | | -import java.util.stream.Stream; |
| 18 | +import java.security.Principal; |
21 | 19 |
|
22 | 20 | import reactor.core.publisher.Mono; |
23 | | - |
| 21 | +import org.springframework.security.core.Authentication; |
24 | 22 | import org.springframework.web.reactive.socket.WebSocketHandler; |
25 | 23 | import org.springframework.web.reactive.socket.WebSocketSession; |
26 | 24 |
|
27 | 25 | /** |
28 | 26 | * @author Greg Turnquist |
29 | 27 | */ |
30 | 28 | // tag::code[] |
31 | | -abstract class UserParsingHandshakeHandler |
| 29 | +abstract class AuthorizedWebSocketHandler |
32 | 30 | implements WebSocketHandler { |
33 | 31 |
|
34 | | - private final Map<String, String> userMap; |
35 | | - |
36 | | - UserParsingHandshakeHandler() { |
37 | | - this.userMap = new HashMap<>(); |
38 | | - } |
39 | | - |
40 | 32 | @Override |
41 | 33 | public final Mono<Void> handle(WebSocketSession session) { |
42 | | - |
43 | | - this.userMap.put(session.getId(), |
44 | | - Stream.of(session.getHandshakeInfo().getUri() |
45 | | - .getQuery().split("&")) |
46 | | - .map(s -> s.split("=")) |
47 | | - .filter(strings -> strings[0].equals("user")) |
48 | | - .findFirst() |
49 | | - .map(strings -> strings[1]) |
50 | | - .orElse("")); |
51 | | - |
52 | | - return handleInternal(session); |
| 34 | + return session.getHandshakeInfo().getPrincipal() |
| 35 | + .filter(this::isAuthorized) |
| 36 | + .then(doHandle(session)); |
53 | 37 | } |
54 | 38 |
|
55 | | - abstract protected Mono<Void> handleInternal( |
56 | | - WebSocketSession session); |
57 | | - |
58 | | - String getUser(String id) { |
59 | | - return userMap.get(id); |
| 39 | + private boolean isAuthorized(Principal principal) { |
| 40 | + Authentication authentication = (Authentication) principal; |
| 41 | + return authentication.isAuthenticated() && |
| 42 | + authentication.getAuthorities().contains("ROLE_USER"); |
60 | 43 | } |
| 44 | + |
| 45 | + abstract protected Mono<Void> doHandle( |
| 46 | + WebSocketSession session); |
61 | 47 | } |
62 | 48 | // end::code[] |
0 commit comments