2017-11-01 18 views
0

角度とスプリングセキュリティが新しくなりました。角度認証フォームページから基本認証を使用して残りのエンドポイントにログインしようとすると、CORSに問題があります。私の角度コードはhttp://localhost:4200で、残りはhttp://localhost:8181にあります。私の角度のあるログインフォームは、ログインコントローラで指定したhttp://localhost:8181/tokenへのリクエストを試みます。 -スプリングCORSと角度が動作しません:HTTPステータスコード403エラー

ロードに失敗しましたhttp://localhost:8181/token:プリフライト要求に対する応答がアクセス制御チェックに合格していません:いいえ 'Access-Control-Allow-Origin'ヘッダーがありません。サーバー側にコルス構成を追加しましたが、要求されたリソースに存在します。 Origin 'http://localhost:4200'はアクセスできません。応答は、HTTPステータスコード403

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

}

(スプリング)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

@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()); 
    } 
} 
+0

CORSは(https://spring.io/understanding/CORS)無効にしているようだ – Zooly

+0

上記のコードブロックでCORSの設定をSecurityConfigクラスに追加しました –

+0

問題はあなたの認証メカニズムにあり、何らかの形でユーザーを認証できません。したがって、私は、クラスがFilterインターフェイスを実装し、春のCorConfigurationSourceの代わりにCorsの処理のためのすべてのリクエスト/レスポンスに対してfilterChain.doFilterを実行する従来のアプローチを使用すると、403ステータス –

答えて

0

を使用してください。それはあなたのために正常に動作するはずです。

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

春のセキュリティ/認証を使用しているためです。 setAllowCredentials(true)を使用する必要があります。

+0

ありがとうございます。それは感謝として動作します:) –

0

Use

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

代わりに使用してください。お使いのコントローラ内部の

+1

しかし、私はグローバルレベルでcors設定を追加したいと思います。コントローラーにはありません。 –

0

@valueを( "$ {cors.site.enable}") プライベート文字列サイトファイル.propertiesファイルからの値を使用します。

@crossOrigin(サイト)

関連する問題