2017-11-01 2 views
0

각도 및 스프링 보안이 처음입니다. 앵글 로그인 양식 페이지에서 기본 인증을 사용하여 나머지 끝점에 로그인 할 때 CORS에 문제가 있습니다. 내 각진 코드는 http://localhost:4200이고 나머지는 http://localhost:8181입니다. 저의 로그인 양식은 로그인 컨트롤러에 지정한 http://localhost:8181/token에게 요청을 시도합니다. -스프링 CORS 및 각도가 작동하지 않음 : HTTP 상태 코드 403 오류

http://localhost:8181/token로드 실패 : 프리 플라이트 요청에 대한 응답으로 액세스 제어 검사를 통과하지 못했습니다. '액세스 제어 허용 원점'헤더가 없습니다. 요청한 리소스에 있습니다. 따라서 원점 '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

비활성화 될 것으로 보인다 코드 블록에서 위에 표시된 것처럼 SecurityConfig 클래스에 CORS 구성을 추가했습니다. –

+0

인증 메커니즘에 문제가있는 것 같습니다. 어떻게 든 사용자를 인증 할 수 없습니다. 그래서 내가 클래스를 필터 인터페이스를 구현하고있는 모든 요청/응답에 대한 모든 요청/응답에 대한 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 (site)