From 4354a43af778b0f4191942671c7ce97e2d34ecf3 Mon Sep 17 00:00:00 2001 From: "aditya.chandel" <> Date: Sun, 16 Feb 2025 00:32:50 -0700 Subject: [PATCH] Make WS work with Auth --- .../booklore/config/WebSocketConfig.java | 19 +++++- .../security/JwtAuthenticationFilter.java | 8 ++- .../config/security/SecurityConfig.java | 1 + .../security/WebSocketAuthInterceptor.java | 65 +++++++++++++++++++ .../book-card/book-card.component.html | 2 +- .../book-card/book-card.component.ts | 5 +- .../book-table/book-table.component.html | 2 +- .../book-table/book-table.component.ts | 7 +- .../book-searcher.component.html | 2 +- .../book-searcher/book-searcher.component.ts | 7 +- .../src/app/core/service/auth.service.ts | 39 +++++++++-- .../layout-topbar/app.topbar.component.ts | 5 +- .../src/app/login/login.component.html | 30 ++++++--- .../src/app/login/login.component.scss | 24 +++---- booklore-ui/src/app/login/login.component.ts | 14 +++- .../metadata-editor.component.html | 2 +- .../metadata-editor.component.ts | 4 +- .../metadata-viewer.component.html | 6 +- .../metadata-viewer.component.ts | 3 +- booklore-ui/src/app/secure-pipe.ts | 19 ++++++ .../websocket/rx-stomp-service-factory.ts | 11 ++-- .../app/shared/websocket/rx-stomp.config.ts | 47 +++++--------- .../app/shared/websocket/rx-stomp.service.ts | 8 ++- booklore-ui/src/main.ts | 2 + 24 files changed, 243 insertions(+), 89 deletions(-) create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/config/security/WebSocketAuthInterceptor.java create mode 100644 booklore-ui/src/app/secure-pipe.ts diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/WebSocketConfig.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/WebSocketConfig.java index 80b1c1c17..722e7bc1a 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/WebSocketConfig.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/WebSocketConfig.java @@ -1,15 +1,25 @@ package com.adityachandel.booklore.config; +import com.adityachandel.booklore.config.security.WebSocketAuthInterceptor; +import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.simp.config.ChannelRegistration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; +@Slf4j @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { + private final WebSocketAuthInterceptor webSocketAuthInterceptor; + + public WebSocketConfig(WebSocketAuthInterceptor webSocketAuthInterceptor) { + this.webSocketAuthInterceptor = webSocketAuthInterceptor; + } + @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); @@ -19,6 +29,11 @@ public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws").setAllowedOrigins("*"); - System.out.println("WebSocket endpoint registered at /ws"); + log.info("WebSocket endpoint registered at /ws"); } -} + + @Override + public void configureClientInboundChannel(ChannelRegistration registration) { + registration.interceptors(webSocketAuthInterceptor); + } +} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/JwtAuthenticationFilter.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/JwtAuthenticationFilter.java index 4011fea8a..2dd571488 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/JwtAuthenticationFilter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/JwtAuthenticationFilter.java @@ -28,8 +28,12 @@ public class JwtAuthenticationFilter extends OncePerRequestFilter { private final UserRepository userRepository; @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) - throws ServletException, IOException { + protected boolean shouldNotFilter(HttpServletRequest request) { + return "websocket".equalsIgnoreCase(request.getHeader("Upgrade")); + } + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String token = getJwtFromRequest(request); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java index d5f4a3838..263b018fb 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/SecurityConfig.java @@ -34,6 +34,7 @@ public class SecurityConfig { .csrf(AbstractHttpConfigurer::disable) .authorizeHttpRequests(auth -> auth .requestMatchers("/api/v1/auth/register", "/api/v1/auth/login").permitAll() + .requestMatchers("/ws/**").permitAll() .anyRequest().authenticated() ) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/WebSocketAuthInterceptor.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/WebSocketAuthInterceptor.java new file mode 100644 index 000000000..40183a6ba --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/WebSocketAuthInterceptor.java @@ -0,0 +1,65 @@ +package com.adityachandel.booklore.config.security; + +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.simp.stomp.StompCommand; +import org.springframework.messaging.simp.stomp.StompHeaderAccessor; +import org.springframework.messaging.support.ChannelInterceptor; +import org.springframework.messaging.support.MessageHeaderAccessor; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.stereotype.Component; + +import java.util.Collections; +import java.util.List; + +@AllArgsConstructor +@Slf4j +@Component +@Order(Ordered.HIGHEST_PRECEDENCE + 99) +public class WebSocketAuthInterceptor implements ChannelInterceptor { + + private final JwtUtils jwtUtils; + + @Override + public Message preSend(Message message, MessageChannel channel) { + StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); + + if (accessor != null && StompCommand.CONNECT.equals(accessor.getCommand())) { + List authHeaders = accessor.getNativeHeader("Authorization"); + + if (authHeaders == null || authHeaders.isEmpty()) { + log.warn("WebSocket connection rejected: No Authorization header"); + throw new IllegalArgumentException("Missing Authorization header"); + } + + String token = authHeaders.get(0).replace("Bearer ", ""); + Authentication auth = authenticateToken(token); + + if (auth == null) { + log.warn("WebSocket connection rejected: Invalid token"); + throw new IllegalArgumentException("Invalid Authorization token"); + } + + accessor.setUser(auth); + log.info("WebSocket authentication successful for user: {}", auth.getName()); + } + + return message; + } + + private Authentication authenticateToken(String token) { + if (!jwtUtils.validateToken(token)) { + return null; + } + String username = jwtUtils.extractUsername(token); + List authorities = Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")); + + return new UsernamePasswordAuthenticationToken(username, null, authorities); + } +} \ No newline at end of file diff --git a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.html b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.html index 68a542af0..470a41ef9 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.html +++ b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.html @@ -4,7 +4,7 @@ (mouseout)="isHovered = false">
Cover of {{ book.metadata?.title }} diff --git a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts index ca9e67684..fe833de00 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts +++ b/booklore-ui/src/app/book/components/book-browser/book-card/book-card.component.ts @@ -13,14 +13,15 @@ import {MetadataFetchOptionsComponent} from '../../../../metadata/metadata-optio import {MetadataRefreshType} from '../../../../metadata/model/request/metadata-refresh-type.enum'; import {MetadataRefreshRequest} from '../../../../metadata/model/request/metadata-refresh-request.model'; import {UrlHelperService} from '../../../../utilities/service/url-helper.service'; -import {NgIf} from '@angular/common'; +import {AsyncPipe, NgIf} from '@angular/common'; +import {SecurePipe} from '../../../../secure-pipe'; @Component({ selector: 'app-book-card', templateUrl: './book-card.component.html', styleUrls: ['./book-card.component.scss'], - imports: [Button, MenuModule, CheckboxModule, FormsModule, NgIf], + imports: [Button, MenuModule, CheckboxModule, FormsModule, NgIf, AsyncPipe, SecurePipe], standalone: true }) export class BookCardComponent implements OnInit { diff --git a/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.html b/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.html index 0985e7ef9..3d984b068 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.html +++ b/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.html @@ -35,7 +35,7 @@ - Book Cover + Book Cover {{ metadata.title }} {{ getAuthorNames(metadata.authors) }} diff --git a/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.ts b/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.ts index 0bcf035cc..a049930b4 100644 --- a/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.ts +++ b/booklore-ui/src/app/book/components/book-browser/book-table/book-table.component.ts @@ -1,12 +1,13 @@ import {Component, EventEmitter, inject, Input, OnChanges, Output} from '@angular/core'; import {TableModule} from 'primeng/table'; -import {NgIf} from '@angular/common'; +import {AsyncPipe, NgIf} from '@angular/common'; import {Rating} from 'primeng/rating'; import {FormsModule} from '@angular/forms'; import {Book} from '../../../model/book.model'; import {SortOption} from '../../../model/sort.model'; import {MetadataDialogService} from '../../../../metadata/service/metadata-dialog.service'; import {UrlHelperService} from '../../../../utilities/service/url-helper.service'; +import {SecurePipe} from '../../../../secure-pipe'; @Component({ selector: 'app-book-table', @@ -16,7 +17,9 @@ import {UrlHelperService} from '../../../../utilities/service/url-helper.service TableModule, NgIf, Rating, - FormsModule + FormsModule, + SecurePipe, + AsyncPipe ], styleUrl: './book-table.component.scss' }) diff --git a/booklore-ui/src/app/book/components/book-searcher/book-searcher.component.html b/booklore-ui/src/app/book/components/book-searcher/book-searcher.component.html index 00bf280be..76a7a3f2e 100644 --- a/booklore-ui/src/app/book/components/book-searcher/book-searcher.component.html +++ b/booklore-ui/src/app/book/components/book-searcher/book-searcher.component.html @@ -17,7 +17,7 @@
- Book Cover + Book Cover

{{ book.metadata?.title | slice:0:70 }}

diff --git a/booklore-ui/src/app/book/components/book-searcher/book-searcher.component.ts b/booklore-ui/src/app/book/components/book-searcher/book-searcher.component.ts index 5125cfcef..bea16a78b 100644 --- a/booklore-ui/src/app/book/components/book-searcher/book-searcher.component.ts +++ b/booklore-ui/src/app/book/components/book-searcher/book-searcher.component.ts @@ -6,10 +6,11 @@ import {FormsModule} from '@angular/forms'; import {InputTextModule} from 'primeng/inputtext'; import {BookService} from '../../service/book.service'; import {Button} from 'primeng/button'; -import {NgForOf, NgIf, SlicePipe} from '@angular/common'; +import {AsyncPipe, NgForOf, NgIf, SlicePipe} from '@angular/common'; import {MetadataDialogService} from '../../../metadata/service/metadata-dialog.service'; import {Divider} from 'primeng/divider'; import {UrlHelperService} from '../../../utilities/service/url-helper.service'; +import {SecurePipe} from '../../../secure-pipe'; @Component({ selector: 'app-book-searcher', @@ -21,7 +22,9 @@ import {UrlHelperService} from '../../../utilities/service/url-helper.service'; NgIf, NgForOf, SlicePipe, - Divider + Divider, + AsyncPipe, + SecurePipe ], styleUrls: ['./book-searcher.component.scss'], standalone: true diff --git a/booklore-ui/src/app/core/service/auth.service.ts b/booklore-ui/src/app/core/service/auth.service.ts index a65934f11..af76a6716 100644 --- a/booklore-ui/src/app/core/service/auth.service.ts +++ b/booklore-ui/src/app/core/service/auth.service.ts @@ -1,17 +1,27 @@ -import { Injectable } from '@angular/core'; -import {HttpClient} from '@angular/common/http'; -import {Observable} from 'rxjs'; +import { Injectable, Injector } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { Observable, tap } from 'rxjs'; +import { RxStompService } from '../../shared/websocket/rx-stomp.service'; +import { createRxStompConfig } from '../../shared/websocket/rx-stomp.config'; @Injectable({ - providedIn: 'root' + providedIn: 'root', }) export class AuthService { private apiUrl = 'http://localhost:7050/api/v1/auth/login'; + private rxStompService?: RxStompService; - constructor(private http: HttpClient) {} + constructor(private http: HttpClient, private injector: Injector) {} login(credentials: { username: string; password: string }): Observable { - return this.http.post(this.apiUrl, credentials); + return this.http.post<{ token: string }>(this.apiUrl, credentials).pipe( + tap((response) => { + if (response.token) { + this.saveToken(response.token); + this.startWebSocket(); + } + }) + ); } saveToken(token: string): void { @@ -24,5 +34,22 @@ export class AuthService { logout(): void { localStorage.removeItem('token'); + this.getRxStompService().deactivate(); + } + + private startWebSocket(): void { + const token = this.getToken(); + if (token) { + const rxStompService = this.getRxStompService(); + rxStompService.configure(createRxStompConfig(this)); + rxStompService.activate(); + } + } + + private getRxStompService(): RxStompService { + if (!this.rxStompService) { + this.rxStompService = this.injector.get(RxStompService); + } + return this.rxStompService; } } diff --git a/booklore-ui/src/app/layout/component/layout-topbar/app.topbar.component.ts b/booklore-ui/src/app/layout/component/layout-topbar/app.topbar.component.ts index b27f2a672..b8b8e68b5 100644 --- a/booklore-ui/src/app/layout/component/layout-topbar/app.topbar.component.ts +++ b/booklore-ui/src/app/layout/component/layout-topbar/app.topbar.component.ts @@ -16,6 +16,7 @@ import {Divider} from 'primeng/divider'; import {ThemeConfiguratorComponent} from '../theme-configurator/theme-configurator.component'; import {LiveNotificationBoxComponent} from '../../../core/component/live-notification-box/live-notification-box.component'; import {BookUploaderComponent} from '../../../utilities/component/book-uploader/book-uploader.component'; +import {AuthService} from '../../../core/service/auth.service'; @Component({ selector: 'app-topbar', @@ -49,7 +50,7 @@ export class AppTopBarComponent implements OnDestroy { @ViewChild('topbarmenu') menu!: ElementRef; constructor(public layoutService: LayoutService, public dialogService: PrimeDialogService, - private eventService: EventService, private router: Router) { + private eventService: EventService, private router: Router, private authService: AuthService) { this.eventService.eventHighlight$.subscribe(highlight => { this.eventHighlight = highlight; }); @@ -115,7 +116,7 @@ export class AppTopBarComponent implements OnDestroy { } logout() { - localStorage.removeItem('token'); + this.authService.logout(); window.location.href = '/login'; } } diff --git a/booklore-ui/src/app/login/login.component.html b/booklore-ui/src/app/login/login.component.html index 2d739c78f..7864d6a12 100644 --- a/booklore-ui/src/app/login/login.component.html +++ b/booklore-ui/src/app/login/login.component.html @@ -1,13 +1,25 @@ diff --git a/booklore-ui/src/app/login/login.component.scss b/booklore-ui/src/app/login/login.component.scss index 1c9f05dc4..05e075ada 100644 --- a/booklore-ui/src/app/login/login.component.scss +++ b/booklore-ui/src/app/login/login.component.scss @@ -1,27 +1,19 @@ .login-container { - @apply flex flex-col items-center justify-center min-h-screen bg-gradient-to-br from-blue-200 to-blue-500; + @apply flex flex-col items-center justify-center min-h-screen bg-gradient-to-br from-orange-200 to-gray-700; - h2 { - @apply text-2xl font-bold text-gray-700 mb-4; + .login-card { + @apply w-96 shadow-lg rounded-xl; } form { - @apply bg-white p-6 rounded-2xl shadow-lg w-96 flex flex-col gap-4; + @apply flex flex-col gap-4; - label { - @apply text-sm font-semibold text-gray-600; + .p-field { + @apply flex flex-col gap-1; } - input { - @apply w-full p-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400; - } - - button { - @apply w-full bg-blue-500 text-white py-2 rounded-lg font-semibold hover:bg-blue-600 transition duration-300; - } - - .error { - @apply text-red-500 text-sm font-medium mt-2; + p-button { + @apply mt-2; } } } diff --git a/booklore-ui/src/app/login/login.component.ts b/booklore-ui/src/app/login/login.component.ts index 9f58f99c3..0836b5f3a 100644 --- a/booklore-ui/src/app/login/login.component.ts +++ b/booklore-ui/src/app/login/login.component.ts @@ -3,12 +3,24 @@ import {AuthService} from '../core/service/auth.service'; import {Router} from '@angular/router'; import {FormsModule} from '@angular/forms'; import {NgIf} from '@angular/common'; +import {Card} from 'primeng/card'; +import {Password} from 'primeng/password'; +import {Button} from 'primeng/button'; +import {Message} from 'primeng/message'; +import {PrimeTemplate} from 'primeng/api'; +import {InputText} from 'primeng/inputtext'; @Component({ selector: 'app-login', imports: [ FormsModule, - NgIf + NgIf, + Card, + Password, + Button, + Message, + PrimeTemplate, + InputText ], templateUrl: './login.component.html', styleUrl: './login.component.scss' diff --git a/booklore-ui/src/app/metadata/book-metadata-center/metadata-editor/metadata-editor.component.html b/booklore-ui/src/app/metadata/book-metadata-center/metadata-editor/metadata-editor.component.html index 6199d3769..6c733a0b6 100644 --- a/booklore-ui/src/app/metadata/book-metadata-center/metadata-editor/metadata-editor.component.html +++ b/booklore-ui/src/app/metadata/book-metadata-center/metadata-editor/metadata-editor.component.html @@ -10,7 +10,7 @@
Image
- Cover of {{ metadata.title }} + Cover of {{ metadata.title }}
diff --git a/booklore-ui/src/app/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts b/booklore-ui/src/app/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts index 6b9f1134a..e3a634fd3 100644 --- a/booklore-ui/src/app/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts +++ b/booklore-ui/src/app/metadata/book-metadata-center/metadata-viewer/metadata-viewer.component.ts @@ -10,13 +10,14 @@ import {Tag} from 'primeng/tag'; import {BookMetadata} from '../../../book/model/book.model'; import {Divider} from 'primeng/divider'; import {UrlHelperService} from '../../../utilities/service/url-helper.service'; +import {SecurePipe} from '../../../secure-pipe'; @Component({ selector: 'app-metadata-viewer', standalone: true, templateUrl: './metadata-viewer.component.html', styleUrl: './metadata-viewer.component.scss', - imports: [Button, NgForOf, NgIf, AsyncPipe, Rating, FormsModule, Tag, Divider] + imports: [Button, NgForOf, NgIf, AsyncPipe, Rating, FormsModule, Tag, Divider, SecurePipe] }) export class MetadataViewerComponent { diff --git a/booklore-ui/src/app/secure-pipe.ts b/booklore-ui/src/app/secure-pipe.ts new file mode 100644 index 000000000..6b6db7bf5 --- /dev/null +++ b/booklore-ui/src/app/secure-pipe.ts @@ -0,0 +1,19 @@ +import { Pipe, PipeTransform } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; +import { DomSanitizer, SafeUrl } from '@angular/platform-browser'; +import { Observable } from 'rxjs'; +import { map } from 'rxjs/operators'; + +@Pipe({ + name: 'secure', + pure: true +}) +export class SecurePipe implements PipeTransform { + constructor(private http: HttpClient, private sanitizer: DomSanitizer) {} + + transform(url: string): Observable { + return this.http.get(url, { responseType: 'blob' }).pipe( + map(blob => this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(blob))) + ); + } +} diff --git a/booklore-ui/src/app/shared/websocket/rx-stomp-service-factory.ts b/booklore-ui/src/app/shared/websocket/rx-stomp-service-factory.ts index 1906e2acc..0801dd29f 100644 --- a/booklore-ui/src/app/shared/websocket/rx-stomp-service-factory.ts +++ b/booklore-ui/src/app/shared/websocket/rx-stomp-service-factory.ts @@ -1,9 +1,10 @@ import { RxStompService } from './rx-stomp.service'; -import { rxStompConfig } from './rx-stomp.config'; +import { createRxStompConfig } from './rx-stomp.config'; +import {AuthService} from '../../core/service/auth.service'; -export function rxStompServiceFactory() { - const rxStomp = new RxStompService(); - rxStomp.configure(rxStompConfig); - rxStomp.activate(); +export function rxStompServiceFactory(authService: AuthService) { + const rxStomp = new RxStompService(authService); + const stompConfig = createRxStompConfig(authService); + rxStomp.configure(stompConfig); return rxStomp; } diff --git a/booklore-ui/src/app/shared/websocket/rx-stomp.config.ts b/booklore-ui/src/app/shared/websocket/rx-stomp.config.ts index f74b1abca..41a1f458a 100644 --- a/booklore-ui/src/app/shared/websocket/rx-stomp.config.ts +++ b/booklore-ui/src/app/shared/websocket/rx-stomp.config.ts @@ -1,31 +1,18 @@ -import {RxStompConfig} from '@stomp/rx-stomp'; -import {API_CONFIG} from '../../config/api-config'; +import { RxStompConfig } from '@stomp/rx-stomp'; +import { API_CONFIG } from '../../config/api-config'; +import {AuthService} from '../../core/service/auth.service'; -export const rxStompConfig: RxStompConfig = { - // Which server? - brokerURL: API_CONFIG.BROKER_URL, - - // Headers - // Typical keys: login, passcode, host - connectHeaders: { - login: 'guest', - passcode: 'guest', - }, - - // How often to heartbeat? - // Interval in milliseconds, set to 0 to disable - heartbeatIncoming: 0, // Typical value 0 - disabled - heartbeatOutgoing: 20000, // Typical value 20000 - every 20 seconds - - // Wait in milliseconds before attempting auto reconnect - // Set to 0 to disable - // Typical value 500 (500 milli seconds) - reconnectDelay: 200, - - // Will log diagnostics on console - // It can be quite verbose, not recommended in production - // Skip this key to stop logging to console - debug: (msg: string): void => { - //console.log(new Date(), msg); - }, -}; +export function createRxStompConfig(authService: AuthService): RxStompConfig { + return { + brokerURL: API_CONFIG.BROKER_URL, + connectHeaders: { + Authorization: `Bearer ${authService.getToken()}`, + }, + heartbeatIncoming: 0, + heartbeatOutgoing: 20000, + reconnectDelay: 200, + debug: (msg: string): void => { + //console.log(new Date(), msg); + }, + }; +} diff --git a/booklore-ui/src/app/shared/websocket/rx-stomp.service.ts b/booklore-ui/src/app/shared/websocket/rx-stomp.service.ts index 90c45720a..bd670b08b 100644 --- a/booklore-ui/src/app/shared/websocket/rx-stomp.service.ts +++ b/booklore-ui/src/app/shared/websocket/rx-stomp.service.ts @@ -1,13 +1,15 @@ import { Injectable } from '@angular/core'; import { RxStomp } from '@stomp/rx-stomp'; +import { AuthService } from '../../core/service/auth.service'; +import { createRxStompConfig } from './rx-stomp.config'; @Injectable({ providedIn: 'root', }) export class RxStompService extends RxStomp { - - constructor() { + constructor(private authService: AuthService) { super(); + const stompConfig = createRxStompConfig(this.authService); + this.configure(stompConfig); } - } diff --git a/booklore-ui/src/main.ts b/booklore-ui/src/main.ts index 1e023ffc2..ed04cfdbf 100644 --- a/booklore-ui/src/main.ts +++ b/booklore-ui/src/main.ts @@ -12,6 +12,7 @@ import { AppComponent } from './app/app.component'; import Aura from '@primeng/themes/aura'; import { routes } from './app/app.routes'; import {AuthInterceptorService} from './app/auth-interceptor.service'; +import {AuthService} from './app/core/service/auth.service'; bootstrapApplication(AppComponent, { providers: [ @@ -23,6 +24,7 @@ bootstrapApplication(AppComponent, { { provide: RxStompService, useFactory: rxStompServiceFactory, + deps: [AuthService], }, { provide: RouteReuseStrategy,