2017-03-02 351 views
2

首先,我已经检查了this page的问题,我尝试了他的解决方案,但在最后,我仍然有同样的问题。Angular2与弹簧靴和弹簧安全

XMLHttpRequest无法加载http://localhost:8080/login。 对预检请求的响应未通过访问控制检查: 请求的资源上没有“Access-Control-Allow-Origin”标头。 原产地'http://localhost:3000'因此不允许访问。 响应了HTTP状态代码403

不过,我把一个access-control无处不在,所以我不明白为什么是这样的。

我的代码看起来像这样(我希望我会投入足够的你):

在转角,我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; 
    } 

我也想,如果认证成功返回一个布尔值,但我真的不知道如何知道它是否有效,所以我现在就这样做(并且总是如此)。

然后,在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创建Angular2应用程序?因为除了当我添加安全性时,所有东西都可以在Spring Boot和Angular之间使用。

+0

我删除了'.addFilterBefore(新CorsFilter(),ChannelProcessingFilter.class);'但是'corsConfigurationSource',我在我的问题写的是我在我的代码中写道。我完全错了吗? –

+1

这次我没有任何Cors消息,但一个新的错误: '在位置0的JSON中的意外的标记< –

+1

我得到你对'corsConfigurationSource'的评论,是的,它是在我的代码中的类中。然而,对于Spring Security日志,调试已启用,但在Java端看不到任何东西,而在Angular端,我仍然看到403错误。 但是,当我删除'.addFilter ...'我不再有这个错误,但与意外的令牌问题。 –

回答

1

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

.cors().and() 
+0

我做到了,他正在寻找'org.springframework.web.filter.CorsFilter',我的CorsFilter在'org.cedric.filters.CorsFilter'中。 因此,错误如下所示: 创建名为'springSecurityFilterChain'的bean的错误 –

+0

请阅读http://docs.spring.io/spring-security/site/docs/current/reference/html/cors。html –

+0

我在我的问题中添加了这段代码,因为在评论中它很难读。 而仍然是同样的问题,我误解了一些东西? –