I am developing a api for websocket using SpringBoot and when i am trying to access or connecting websocket using Angular its always giving 403 Forbidden.But same api example http://localhost:8080/ws is connecting through postman by passing Basic auth but its failed from angular
error
Java code
WebSocketConfig
‘’’
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOrigins("http://localhost:4200")
.setAllowedOriginPatterns("http://localhost:*")
.withSockJS();
}
@Bean
@Primary
public ThreadPoolTaskExecutor customClientInboundChannelExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("custom-clientInbound-");
return executor;
}
}
‘’’
webconfig
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/simulation-alert/**")
.allowedOrigins("http://localhost:4200")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("*")
.allowCredentials(true);
}
}
Angular
export class WebSocketService {
private socket: WebSocket | null = null; // Initialize with null
private messageSubject = new BehaviorSubject(null);
message$ = this.messageSubject.asObservable();
constructor(private http: HttpClient) {}
// Step 1: Authenticate via HTTP request
authenticate() {
const myHeaders = new Headers();
myHeaders.append(‘Authorization’, ‘Basic …==’);
myHeaders.append(‘Cookie’, ‘JSESSIONID=633580394D50A0EFC7793BF02FAFB889’);
const requestOptions: RequestInit = {
method: ‘GET’,
headers: myHeaders,
redirect: ‘follow’
};
fetch(‘http://localhost:8080/ws’, requestOptions)
.then((response: Response) => { // Explicitly type the parameter as Response
if (response.ok) {
// Step 2: After successful authentication, establish WebSocket connection
this.connectWebSocket();
} else {
throw new Error(‘Authentication failed’);
}
})
.catch((error) => console.error(‘Authentication error:’, error));
}
// Step 2: Establish WebSocket connection after authentication
private connectWebSocket() {
this.socket = new WebSocket(‘ws://localhost:8080/simulation-alert’); // Use your WebSocket URL
this.socket.onopen = () => {
console.log('WebSocket connection established');
};
this.socket.onmessage = (event) => {
const message = JSON.parse(event.data);
this.messageSubject.next(message); // Emit received message
};
this.socket.onerror = (error) => {
console.error('WebSocket error:', error);
};
this.socket.onclose = (event) => {
console.log('WebSocket connection closed:', event);
};
}