2017-03-02 33 views
2

まず、私はすでにthis pageに質問をチェックしています。私は彼の解決策を試していますが、最後には同じ問題が残っています。Angular2 with Spring Boot and Spring Security

XMLHttpRequestはロードできませんhttp://localhost:8080/login。 プリフライト要求への応答がアクセス制御チェックに合格しません: 要求されたリソースに「Access-Control-Allow-Origin」ヘッダーがありません。 発信元 'http://localhost:3000'はアクセスできません。 応答は、私はそれがこのようなものだ、なぜ私は理解していないどこでもaccess-controlを入れて、しかし、HTTPステータスコード403

を持っていました。

私のコードは、(私は私があなたのために十分に置くことを願っています)、このようになります

:角度で

、私の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; 
    } 

私はまた、認証が成功した場合はブール値を返すようにしたいが、私それが動作するかどうかを知る方法を本当に知っていないので、私は今のところそれを好きです(そして、それはいつも真です)。だから

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

:私のLoginSuccessHandlerで

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

@Configuration 
@EnableWebMvc 
class WebConfig extends WebMvcConfigurerAdapter { 
} 

、セキュリティのために、私はこれを得た

はその後、Javaで、私はこのコードを持っています何が問題なのか?または、SpringブートとSpring SecurityでAngular2アプリケーションを作成する方法について教えてください。セキュリティを追加する場合を除いて、すべてがSpring BootとAngularの間で動作するためです。

+0

に以下を追加します;'が、私は私の質問に書いたものを 'corsConfigurationSource'は、どのようなIです私のコードに書きました。私は完全に間違っていましたか? –

+1

今回は私にCorsメッセージはありませんが、新しいエラーがあります: '予期せぬトークン

+1

' corsConfigurationSource'についてあなたが言っていることを得て、それは私のコードのクラスです。しかし、Spring Securityのログでは、Debugは有効になっていますが、Java側では何も見えません。Angular側ではまだ403エラーが表示されます。 しかし、 '.addFilter ... 'を削除すると、私はもはやこのエラーではなく、予期しないトークンに問題があります。 –

答えて

1

私は `.addFilterBefore(新CorsFilter()、ChannelProcessingFilter.class)を取り外し、あなたのconfigureメソッド

.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

私の質問にこのコードを追加します。コメントでは読みづらいので、このコードを追加します。 まだ同じ問題ですが、私は何かを誤解していますか? –