Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java CORS错误和403对JWT令牌的响应_Java_Spring_Angular_Spring Boot_Spring Security - Fatal编程技术网

Java CORS错误和403对JWT令牌的响应

Java CORS错误和403对JWT令牌的响应,java,spring,angular,spring-boot,spring-security,Java,Spring,Angular,Spring Boot,Spring Security,我试图通过JWT令牌保护我的Web应用程序,但当我试图从Angular应用程序(localhost:4200)向Spring Boot应用程序(localhost:8080)发出请求时,我遇到以下错误: 仅从消息中我就可以看出这是一个CORS问题,问题是我已经在后端启用了来自不同来源的请求,下面是代码: 更新:我已将选项添加到allowedMethods(),但错误保持不变 @Configuration public class AppConfiguration { @Autowired p

我试图通过JWT令牌保护我的Web应用程序,但当我试图从Angular应用程序(localhost:4200)向Spring Boot应用程序(localhost:8080)发出请求时,我遇到以下错误:

仅从消息中我就可以看出这是一个
CORS
问题,问题是我已经在后端启用了来自不同来源的请求,下面是代码:

更新:我已将选项添加到
allowedMethods()
,但错误保持不变

@Configuration
public class AppConfiguration {

@Autowired
private Environment env;

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:4200")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD","OPTIONS")
                    .allowedHeaders("Content-Type", "Date", "Total-Count", "loginInfo")
                    .exposedHeaders("Content-Type", "Date", "Total-Count", "loginInfo")
                    .maxAge(3600);
        }
    };
}
以下是我的Angular应用程序的代码:

    baseUrl = 'http://localhost:8080/api/';

    constructor(private http: Http) { }


    private postaviHeadere() : RequestOptions{
        let headers = new Headers();

        console.log("***************** Set Headers *****************");
        console.log('Getting token from local storage:');
        console.log(localStorage.getItem('jwt_token'))
        console.log("***********************************************");

        headers.append('JWT_TOKEN', localStorage.getItem('JWT_TOKEN'));
        let options = new RequestOptions({headers : headers});
        console.log(options);
        return options;
    }

    getUserByToken(): any {
        return this.http.get(this.baseUrl + 'user/secured', this.postaviHeadere())
    }

您还必须允许
选项
方法:

@Configuration
public class AppConfiguration {

@Autowired
private Environment env;

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:4200")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS")
                    .allowedHeaders("Content-Type", "Date", "Total-Count", "loginInfo")
                    .exposedHeaders("Content-Type", "Date", "Total-Count", "loginInfo")
                    .maxAge(3600);
        }
    };
}}

我已通过将jwt_令牌添加到配置中解决了此问题:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:4200")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD","OPTIONS")
                    .allowedHeaders("Content-Type", "Date", "Total-Count", "loginInfo","jwt_token")
                    .exposedHeaders("Content-Type", "Date", "Total-Count", "loginInfo", "jwt_token")
                    .maxAge(3600);
        }
    };
}
谢谢大家的帮助

创建java类“CorsFilterConfig”:

然后将其调用到您的Web安全配置:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity

            .csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

            // don't create session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

            .authorizeRequests()

            // Un-secure H2 Database
            .antMatchers("/h2-console/**/**").permitAll()
            //whitelist swagger configuration
            .antMatchers(
                    "/swagger-resources/**",
                    "/api/swagger-resources/**",
                    "/api/**",
                    "/null/**",
                    "/v2/api-docs/**",
                    "/webjars/springfox-swagger-ui/**",
                    "/"
            ).permitAll()

            .anyRequest().authenticated();
    httpSecurity.cors();

    // Custom JWT based security filter
    JwtAuthorizationTokenFilter authenticationTokenFilter =
            new JwtAuthorizationTokenFilter(userDetailsService(), jwtTokenUtil, tokenHeader);
    httpSecurity.addFilterBefore(new CorsFilterConfig(), ChannelProcessingFilter.class);
    httpSecurity
            .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

}

您还应该添加
选项
。应该像
.allowedMethods(“GET”、“POST”、“PUT”、“DELETE”、“HEAD”、“OPTION”)
在执行选项请求时,您会得到403。能否显示该请求的响应头/正文(如果有)。是否在Web服务器级别启用了选项?可能是重复的,谢谢您的快速回复。遗憾的是,这并没有解决我的问题。错误保持不变。选项响应现在是否返回CORS标头?由于您似乎也获得了403状态,因此安全配置可能还有一个额外的问题。你能提供更多关于Spring安全性的配置吗?
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity

            .csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

            // don't create session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

            .authorizeRequests()

            // Un-secure H2 Database
            .antMatchers("/h2-console/**/**").permitAll()
            //whitelist swagger configuration
            .antMatchers(
                    "/swagger-resources/**",
                    "/api/swagger-resources/**",
                    "/api/**",
                    "/null/**",
                    "/v2/api-docs/**",
                    "/webjars/springfox-swagger-ui/**",
                    "/"
            ).permitAll()

            .anyRequest().authenticated();
    httpSecurity.cors();

    // Custom JWT based security filter
    JwtAuthorizationTokenFilter authenticationTokenFilter =
            new JwtAuthorizationTokenFilter(userDetailsService(), jwtTokenUtil, tokenHeader);
    httpSecurity.addFilterBefore(new CorsFilterConfig(), ChannelProcessingFilter.class);
    httpSecurity
            .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

}