XMLHttpRequest 无法加载,对预检请求的响应未通过访问控制

问题描述 投票:0回答:1

首先,我已经在此页面检查了问题,并尝试了该解决方案,但最后我仍然遇到同样的问题。

XMLHttpRequest 无法加载

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

但是,我到处都放了

access-control
,所以我不明白为什么会这样。

我的代码看起来像这样(我希望我能为你提供足够的代码):

在 Angular 中,我的

login.service.ts
:

check(name: string, password: string): boolean {
     let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append('Access-Control-Allow-Origin','*');
    let options = new RequestOptions({headers:headers,withCredentials:true});

    if(this.http.post(this.baseUrl, 
        `username=${name}&password=${password}`,
        {headers:headers})
        .toPromise().then(response=> {
          return {}
        }))
        return true;    

        return false;
  }

如果身份验证成功,我也想返回一个

boolean
,但我真的不知道该怎么做。如果它有效,那么我现在就这样做(而且它总是正确的)。

然后,在Java中,我有这样的代码:

@Configuration
@EnableWebMvc
class WebConfig extends WebMvcConfigurerAdapter {
}

然后为了安全,我得到了这个:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    @Autowired
    private RESTLoginSuccessHandler loginSuccessHandler;

    @Autowired
    private RestLogoutSuccessHandler logoutSuccessHandler;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        //deactivate CSRF and use custom impl for CORS
        httpSecurity
                .cors.and()
                .csrf().disable()
                .addFilterBefore(new CorsFilter(), ChannelProcessingFilter.class);
        //authorize, authenticate rest
        httpSecurity
                .authorizeRequests()
                    .anyRequest().hasRole("USER")
                    .and()
                .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                    .and()
                .formLogin()
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .loginPage("/login")
                    .successHandler(loginSuccessHandler)
                    .permitAll()
                    .and()
                .logout()
                    .logoutSuccessHandler(this.logoutSuccessHandler)
                    .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("rano").password("1234").roles("USER");
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("USER", "ADMIN");
    }
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    
    configuration.setAllowedOrigins(Arrays.asList("http://localhost:8080","http://localhost:3000"));
        
    configuration.setAllowedMethods(Arrays.asList("PUT","DELETE","POST"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

在我的

LoginSuccessHandler

@Component
public class RESTLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private RequestCache requestCache = new HttpSessionRequestCache();

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
            org.springframework.security.core.Authentication authentication) throws IOException, ServletException {

        SavedRequest savedRequest = requestCache.getRequest(request, response);

        if (savedRequest == null) {
            clearAuthenticationAttributes(request);
            return;
        }

        String targetUrlParam = getTargetUrlParameter();
        if (isAlwaysUseDefaultTargetUrl()
                || (targetUrlParam != null && StringUtils.hasText(request.getParameter(targetUrlParam)))) {
            requestCache.removeRequest(request, response);
            clearAuthenticationAttributes(request);
            return;
        }

        clearAuthenticationAttributes(request);
    }

    public void setRequestCache(RequestCache requestCache) {
        this.requestCache = requestCache;
    }
}

那么,你知道问题出在哪里吗?或者如何使用 Spring Boot 和 Spring Security 制作 Angular 2 应用程序?因为 Spring Boot 和 Angular 之间一切正常,除非我添加安全性。

java angular spring-boot spring-security
1个回答
1
投票

将以下内容添加到您的配置方法中

.cors().and()
© www.soinside.com 2019 - 2024. All rights reserved.