【问题标题】:spring CORS and angular not working : HTTP status code 403 errorspring CORS 和 Angular 不起作用:HTTP 状态代码 403 错误
【发布时间】:2018-04-13 22:22:07
【问题描述】:

我是 Angular 和 spring-security 的新手。尝试使用基本身份验证从 Angular 登录表单页面登录到其余端点时,我遇到了 CORS 问题。我的 Angular 代码在 http://localhost:4200 上运行,在 http://localhost:8181 上运行休息端点。我的角度登录表单尝试向我在登录控制器中指定的http://localhost:8181/token 发出请求。即使我在服务器端添加了 cors 配置,我也会收到此错误:-

无法加载http://localhost:8181/token:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:4200' 不允许访问。响应的 HTTP 状态代码为 403。

(角度) 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());
    }
}

【问题讨论】:

  • CORS 似乎已停用 (spring.io/understanding/CORS)
  • 我已经在 SecurityConfig 类中添加了 CORS 配置,如上代码块所示
  • 问题在于您的身份验证机制,不知何故它无法对用户进行身份验证。所以它返回 403 状态
  • 当我使用传统方法时,类实现 Filter 接口并为每个请求/响应执行 filterChain.doFilter 以进行 cors 处理而不是 spring CorConfigurationSource 它工作正常。

标签: java spring angular spring-rest


【解决方案1】:

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

注意:您可以使用 origin address 代替 *

【讨论】:

    【解决方案2】:

    添加

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

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

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

    【讨论】:

      【解决方案3】:

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

      @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;
          }
      

      由于您使用的是弹簧安全/身份验证。您应该使用 setAllowCredentials(true)。

      【讨论】:

      【解决方案4】:

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

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

      使用@crossOrigin(站点)

      【讨论】:

        【解决方案5】:

        使用

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

        改为。

        【讨论】:

        • 但我想在全局级别添加 cors 配置。不在控制器中。
        猜你喜欢
        • 2020-10-08
        • 2016-05-26
        • 1970-01-01
        • 2014-04-05
        • 2014-04-22
        • 1970-01-01
        • 2017-06-27
        • 1970-01-01
        • 2016-02-08
        相关资源
        最近更新 更多