java spring CORS 和 angular 不起作用:HTTP 状态代码 403 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47057592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:29:23  来源:igfitidea点击:

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

javaspringangularspring-rest

提问by Tsetiz Bista

I am new to angular and spring-security.I am having problem with CORS when trying to log in from angular login-form page using basic authentication to the rest endpoint. My Angular code is running on http://localhost:4200and rest end point on http://localhost:8181. My angular login-form tries to make request to http://localhost:8181/tokenwhich I have specified in my login controller. Even though I have added cors configuration in server side, I get this error :-

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

Failed to load 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' is therefore not allowed access. The response had HTTP status code 403.

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

(angular) login.service.ts:-

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

(弹簧)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

登录控制器.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());
    }
}

回答by vsoni

Try this configuration. It should work fine for you.

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

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

Since you are using spring security / authentication. You should use setAllowCredentials(true).

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

回答by Peter Rader

Use

利用

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

instead.

反而。

回答by laynurraa

I was stuck with this problem for 2 days and by adding @CrossOrigin("*")in controllersolved my problem.

我被卡住了这个问题2天,并通过添加@CrossOrigin("*")controller解决我的问题。

note: you can put your origin addressinstead of *

注意:你可以把你的origin address代替*

回答by Amr Alaa

inside your controller use the value from a .properties file

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

@Value("${cors.site.enable}") private String site;

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

use @crossOrigin(site)

使用 @crossOrigin(site)

回答by stfbee

Add

添加

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

to your web.xmlto allow connections from all hosts

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

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

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