当前位置: 首页 > 知识库问答 >
问题:

origin'http://localhost:4200'已被CORS策略用angular和Spring Boot阻止

乐正迪
2023-03-14

我试图用角和Spring做简单的CRUD。我在spring boot应用程序中实现了JWT身份验证。之后,每当我进行插入操作时,它都工作得很好,但每当我试图编辑和删除它时,给出'origin'http://localhost:4200'就被CORS策略‘错误阻止了。为什么我会得到这个错误我在安全配置中添加了'CorsFilter'bean,但它仍然会给我同样的错误。在添加JWT Athentication之前,所有CRUD opration都工作得很好。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception { 
            http.
            cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
        .and().csrf().disable()
                .authorizeRequests()                                                                
                .antMatchers("/**").permitAll()                  
                .antMatchers("/").hasRole("ADMIN")                                      
                .antMatchers("/*").hasRole("USER")
                .and()
                .exceptionHandling()
                .accessDeniedPage("/access-denied")
                .and()
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                .addFilter(new JWTAuthorizationFilter(authenticationManager(), customUserDetailService));
    }
      
    @Bean   
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"));
        configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type", "xsrfheadername","xsrfcookiename"
        ,"X-Requested-With","XSRF-TOKEN","Accept", "x-xsrf-token","withcredentials","x-csrftoken"));
        configuration.setExposedHeaders(Arrays.asList("custom-header1", "custom-header2"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration); 
        return source; 
    }

}
@RestController
public class StudentController {

    @CrossOrigin(origins = "http://localhost:4200")
    @PostMapping(value = "/info")
    public List<Info> addproduct(@RequestBody Info info) {
        signupDAO.add(info);
     
        List<Info> addinfo = signupDAO.getAllInfo();
     
        return addinfo;
    }

    @RequestMapping(value = "/infoDelete/{id}")
    public void deleteStudent(@PathVariable int id) {
        System.out.println("this is deleteid");
            signupDAO.delete(id);    
    }
     
    @PutMapping("/infos/{id}")
    public String updateStudent(@RequestBody Info info, @PathVariable int id) {

        info.setId(id);

        signupDAO.update(info); 

        return "info";
    }
}

LoginService.ts

webInfo(data: Student): Observable<any> {
    const url = '/info';
    return this.httpClient.post(this.serverUrl + url, data);
}

editPlan(data: Student, id: any): Observable<any> {
    const url = `/infos/${id}`;
    return this.httpClient.put(this.serverUrl + url, data);
}

deletePlan(id: any): Observable<any> {
    const url = `/infoDelete/${id}`;
    return this.httpClient.delete(this.serverUrl + url);
}

共有1个答案

卫嘉言
2023-03-14

终于奏效了..

我从SecurityConfig.java中删除了这一行,所有的删除和编辑都工作了。

 cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
 类似资料: