Basic Spring Boot with Angular



I am trying to get a message printed to my web console when I click a button in my Angular UI.

So far I have done:

My Angular Side:

Button:

<button id="b1" mat-raised-button color="primary" type="button"(click)=displayString()>Submit</button>

My .ts file:

  displayString(){
    this.httpClient.post('http://localhost:8080/jpmorgan/editquestionSet',{},{ responseType: "text" })
    .subscribe(response => console.log(response) );
  }

My Springboot side:

SpringSecurityConfig.java:


      @Configuration
      public class WebConfig extends WebMvcConfigurerAdapter {
          @Override
          public void addCorsMappings(CorsRegistry registry) {
              registry.addMapping("/**")
                 .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
          }
      }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic();
    }
    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new 
    UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
       }
}

Controller

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/jpmorgan")
public class ApplicationController {
    
    @Autowired
    private CompilationService compilationService;
    
    @RequestMapping("/editquestionSet")
    public String editquestions() {
        return "Questions Added Successfully";
    }

}

Error That I am getting in Web console:

zone.js:3243 POST http://localhost:8080/jpmorgan/editquestionSet 401 core.js:1449 ERROR HttpErrorResponse {headers: HttpHeaders, status: 401, statusText: “OK”, url: “http://localhost:8080/jpmorgan/editquestionSet”, ok: false, …}

Instead of error, I want a response to coming from the spring app:

** Questions Added Successfully **

Answer

The following means you are requiring authentication.

.anyRequest()
            .authenticated()
            .and()
            .httpBasic();

Try :

.anyRequest().permitAll(); 


Source: stackoverflow