Struggling to link Angular frontend with Java backend?

Trying to make an API call in the backend, but encountering an error with no clear cause identified. The issue arose after configuring the spring security in the backend. The call should activate Preflighted requests OPTION.

@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {    
            http.csrf().disable();
            http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
//            .formLogin().and()
                .httpBasic();
    }
}

Within the frontend code:

  executeHelloWorldServiceWithPathVariable(name) {
    const basicAuthHeaderString = this.createBasicAuthenticationHttpHeader();

    const headers = new HttpHeaders({
        Authorization: basicAuthHeaderString
      });
    return this.http.get<HelloWorldBean>(`http://localhost:8080/hello-world/path-variable/${name}`,
      {headers});
  }

  createBasicAuthenticationHttpHeader() {
    const username = 'start';
    const password = 'end';
    const basicAuthHeaderString = 'Basic ' + window.btoa(username + ':' + password);
    return basicAuthHeaderString;
  }

In the backend, the following inclusion has been made:

@CrossOrigin(origins = "http://localhost:4200")

Despite this, the API call remains unsuccessful. The expected output of an OPTION method is not being received as indicated by the following console logs:

General

Request URL: http://localhost:8080/hello-world/path-variable/start
Referrer Policy: no-referrer-when-downgrade

Response Header

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Length: 0
Date: Tue, 28 Jan 2020 11:11:49 GMT
Expires: 0
Keep-Alive: timeout=60
Pragma: no-cache
WWW-Authenticate: Basic realm="Realm"
WWW-Authenticate: Basic realm="Realm"
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

request head

Accept: application/json, text/plain, / Accept-Encoding: gzip, deflate, br Accept-Language: en,cs;q=0.9,en-US;q=0.8 Authorization: Basicc3RhcnQ6ZWVuZA== Connection: keep-alive Host: localhost:8080 Origin: http://localhost:4200 Referer: http://localhost:4200/welcome/start Sec-Fetch-Mode: cors Sec-Fetch-Site: same-site User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36

The console displays the following error message: https://i.sstatic.net/Ayb4W.png

Answer №1

To enhance your security setup, consider incorporating a CORS policy into your configuration:

@Configuration
@EnableWebSecurity
public class CustomSpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {    
        http.csrf().disable();
        http.cors();
        http.authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
            .anyRequest().authenticated()
            .and()
//          .formLogin().and()
            .httpBasic();
    }
}

Answer №2

If you're working with the

SpringSecurityConfigurationBasicAuth
class, consider implementing this method:

@Bean
  CorsConfigurationSource corsConfigurationSource() {
      CorsConfiguration configuration = new CorsConfiguration();
      configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
      configuration.setAllowedMethods(Arrays.asList("GET","POST"));
      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      source.registerCorsConfiguration("/**", configuration);
      return source;
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular2's ErrorHandler can cause code to malfunction when an error occurs

import { Injectable, ErrorHandler, Inject, Injector } from '@angular/core'; import { MessengerService } from '../services'; import { MessageTypeEnum } from '../../shared'; @Injectable() export class AppErrorHandler extends Er ...

Experiencing difficulty in retrieving data streams in Angular 5 when using the pptxGenjs library

I am working on incorporating images into a PowerPoint file using pptxGenjs in Angular5. While I have successfully retrieved the file with content, my goal is to extract the data from the PowerPoint file in base64 or a similar output format. However, all ...

Displaying each element of the array separately rather than utilizing ngFor

Is there a way to extract just one result from an observable? I know I can easily use ngFor to loop through multiple results, but if I only want to display a single result in a specific part of the page, how can I accomplish that? The primary function in ...

Validating a Java Preferences object against an XSD schema

Is there a way to validate a preferences object using an XSD? Since the preferences file is based on an XML file, it seems like this should be feasible. Any insights or guidance on this would be greatly valued. ...

Having trouble retrieving text from a toasted message using selenium in Java

Recently starting to work with Selenium using Java and facing some challenges. I managed to inspect the element for a Toasted message but I'm uncertain about how to extract the text and validate it properly. Here's the scenario: 1. Click on the ...

Could you explain the variance between ojdbc6.jar and ojdbc7.jar?

Can I use the ojdbc6.jar with JDK 1.7 and Oracle 12c? Or should I opt for ojdbc7.jar instead? Your help is greatly appreciated. ...

Utilizing Prisma's Create Object to Store Return String from Imported Function in Database

In my application, I am utilizing Typescript and have created a test to populate a database using Prisma ORM. Within this test, there is a function that returns a string: const mappingPayload = (data: any) => { let pay = [] const payload = data[0] // ...

Is it possible to utilize an Angular 8 library within an Angular 4 application?

I am currently working on a project that was originally developed in Angular 4. The project is quite large and converting it all to Angular 8 in one go is not feasible. I am planning to tackle this migration in phases. One approach I am considering is conv ...

Is there a way to modify component data in Angular 5 from another component?

I have a dashboard setup where the main component stays consistent across all pages, while another component, the load component, changes based on the router-outlet. My goal is to hide the "manage load" button in the dashboard component if I delete all loa ...

Troubleshooting: Angular CORS Configuration not functioning as expected

I'm currently running an angular application on my local host and attempting to access a REST URL from another domain via a POST request. I have included the 'Content-Type' and 'Authorization' headers in the HTTP request, which see ...

React 18 update causes malfunctioning of react-switch-selector component

I'm facing an issue where the component is not rendering. I attempted to start a new project but it still didn't work. Is there a solution to fix this problem or should I just wait for an update from the original repository? Encountered Error: ...

Angular 12 experiencing CSS alignment issues

In my Angular component, I have the following CSS: .folders { border-left: 5px solid #b8744f; -moz-border-radius: 5px; -webkit-border-radius: 5px; -moz-box-shadow: inset 0 0 1px #fff; -webkit-box-shadow: inset 0 0 1px #fff; /*CORRECTION NEEDED ...

NestJS Bull queues - Failing to secure job completion with a lock

I am currently utilizing Bull in combination with NestJS to manage a jobs queue. Within the process handler, I aim to designate a job as failed instead of completed. However, it appears - after carefully reviewing the documentation as well - that the Job#m ...

Tips for creating a page component in Next.js using props?

I've encountered an issue while trying to properly annotate the parameters of the Home function component. My initial attempt was to use: { events }: { events: Event[] }, but TypeScript is throwing an error, stating that Property 'events' do ...

Detecting the Completion of a Background Thread in Android: A Quick Guide

My app needs to have a feature where users can only talk with the admin for a specific amount of time. Once the time limit is reached, they should be restricted from continuing the conversation and receive a warning message. This functionality should be ...

Assigning a value to an Angular class variable within the subscribe method of an HTTP

Understanding the inner workings of this process has been a challenge for me. I've come across numerous articles that touch on this topic, but they all seem to emphasize the asynchronous nature of setting the class variable only when the callback is t ...

Exploring the distinctions between the Decorator and Mediator design patterns when implemented in JavaScript

After delving into JavaScript patterns, I noticed some interesting differences between Angular 4 and Angular 1.x. Angular 4 employs new patterns that caught my attention. What specific patterns does Angular 4 utilize? Is it possible to incorporate the De ...

The correct way to update component state when handling an onChange event in React using Typescript

How can I update the state for 'selectedValues' in a React component called CheckboxWindow when the onChange() function is triggered by clicking on a checkbox? export const CheckboxWindow: React.FC<Props> = props => { const [selected ...

The one-line character progress bar in JAVA functions in the NetBeans output window, but fails to work in the CMD

Creating a CMD character-based one-line-updating progress bar that will work in both CMD and NetBeans OutputWindow proved to be a challenge for me. Despite many posts claiming it was not possible, I managed to develop my own progress bar that successfully ...

Error: Unable to access properties of null (specifically 'writeValue')

My goal is to retrieve an object by its ID, and if the object does not exist, the component will then register the object. However, when the object does exist, it retrieves the object normally, but then throws the same error again. HTML: <div class="c ...