spring CORS 和 angular 不工作:HTTP 状态代码 403 错误

spring CORS and angular not working : HTTP status code 403 error

我是 angular 的新手,spring-security.I 在尝试使用基本身份验证从 angular 登录表单页面登录时遇到 CORS 问题其余端点。我的 Angular 代码是 http://localhost:4200 and rest end point on http://localhost:8181. My angular login-form tries to make request to http://localhost:8181/token 上的 运行,我在我的登录控制器中指定了它。即使我在服务器端添加了 cors 配置,我也会收到此错误:-

加载失败http://localhost:8181/token: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200'因此不允许访问。响应具有 HTTP 状态代码 403。

(angular) login.service.ts:-

@Injectable()
export class LoginService {
  constructor(private http: Http) {}

  sendCredential(username: string, password: string) {
    const url = 'http://localhost:8181/token';
    const encodedCredential = username + ':' + password;
    const basicHeader = 'Basic ' + btoa(encodedCredential);
    const headers = new Headers();
    headers.append('Content-Type', 'application/x-wwww-form-urlencoded');
    headers.append('Authorization' ,  basicHeader);
    const opts = new RequestOptions({headers: headers});
    return this.http.get(url, opts);
  }

}

(spring) SecurityConfig.java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

private static final String[] PUBLIC_MATCHERS = {
            "/css/**",
            "/js/**",
            "/image/**",
            "/book/**",
            "/user/**"
    };

@Override
    protected void configure(HttpSecurity http) throws Exception{
        http
                .cors().and()
                .csrf().disable()
                .httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers(PUBLIC_MATCHERS)
                .permitAll()
                .anyRequest()
                .authenticated();
    }
 @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST","DELETE","PUT","OPTIONS"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userSecurityService).passwordEncoder(passwordEncoder());
    }

LoginController.java

@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @RequestMapping("/token")
    public Map<String, String> token(HttpSession session, HttpServletRequest request) {
        String remoteHost = request.getRemoteHost();
        int portNumber = request.getRemotePort();
        String remoteAddr = request.getRemoteAddr();

        System.out.println(remoteHost + ":" + portNumber);
        System.out.println(remoteAddr);


        return Collections.singletonMap("token", session.getId());
    }
}

使用

@CrossOrigin("http://your-foreign-site/")
@RequestMapping("/token")

相反。

在您的控制器中使用 .properties 文件中的值

@Value("${cors.site.enable}") 私人字符串网站;

使用@crossOrigin(站点)

试试这个配置。它应该适合你。

@Bean
CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH"));
        configuration.setAllowedHeaders(Arrays.asList("X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

因为您正在使用 spring 安全/身份验证。你应该使用 setAllowCredentials(true).

添加

<mvc:cors>
    <mvc:mapping path="/**" />
</mvc:cors>

到您的 web.xml 以允许来自所有主机的连接

来源:https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

我被这个问题困扰了 2 天,通过在 controller 中添加 @CrossOrigin("*") 解决了我的问题。

注意:您可以将 origin address 代替 *