I have been facing some issues in connecting spring-boot/spring-security with angular 10 in retrieving data and response from the backend.
After logging in, Error is occurs on my default page of my application. I am Stuck on the same error for the past few days. Please Help!
Error is thrown on the backend side: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL contained a potentially malicious String "//" at org.springframework.security.web.firewall.StrictHttpFirewall.rejectedBlacklistedUrls(StrictHttpFirewall.java:369) ~[spring-security-web-5.3.4.RELEASE.jar:5.3.4.RELEASE]
Web Configure File:
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Qualifier("userDetailsService")
@Autowired
private UserDetailsService userDetailsService;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/home/**","/user/login",
"/admin/**").permitAll().anyRequest().authenticated().and().csrf()
.disable().formLogin().permitAll().and().logout().permitAll();
http.cors();
}
@Bean
public AuthenticationManager customAuthenticationManager() throws Exception {
return authenticationManager();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new
UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
return source;
}
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(
"http://localhost:4200")
.allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD").allowedHeaders("*")
;
}
}
User Controller
@CrossOrigin(/* origins = "http://localhost:4200" */origins="*", allowedHeaders = "*")
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
AuthenticationManager authenticationManager;
@SuppressWarnings("rawtypes")
@PostMapping("/login")
public ResponseEntity<Object> login(@RequestBody loginDetails data) {
try {
String username = data.getUsername();
System.out.println("Checking...");
System.out.println(data.getUsername());
System.out.println(data.getPassword());
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, data.getPassword()));
// String token = jwtTokenProvider.createToken(username,
// this.users.findByEmail(username).getRoles());
System.out.println("abcdefg");
Map<Object, Object> model = new HashMap<>();
model.put("username", username);
// model.put("token", token);
return new ResponseEntity<>(model, HttpStatus.OK);
} catch (AuthenticationException e) {
//throw new BadCredentialsException("Invalid email/password supplied");
return new ResponseEntity<>("invalid", HttpStatus.NOT_ACCEPTABLE);
//return false;
}
//return new ResponseEntity<>("valid", HttpStatus.OK);
}
Controller:
@CrossOrigin(origins="http://localhost:4200")
@RestController
@RequestMapping("/home")
public class ElectronicsController {
@GetMapping("/default")
public List<ElectronicSellDAO> homePageDefault() {
System.out.println("Home Default........");
return electronicsService.getDefaultData();
}
}
Angular Service:
this.test=userService.getProducts();
this.test.subscribe(data=>{
console.log(data);
},
error=>{
console.log(error);
})
//get function
getProducts(){
console.log("Get Request");
return this.http.get<any>(`${environment.apiUrl}/home/default`);
}
Error on Console: HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:8080/login", ok: false, …} error: error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} message: "Http failure during parsing for http://localhost:8080/login" name: "HttpErrorResponse" ok: false status: 200 statusText: "OK" url: "http://localhost:8080/login"