Spring zuul gateway с oauth2 sso и angular 2 CORS проблема

Привет, у меня проблема CORS с моей настройкой микросервисов sso, но я не могу понять, почему. Моя установка:

Порт микросервиса oauth 8899:

@Configuration
@Order(-20)
public class EndpointSecurityConfig extends WebSecurityConfigurerAdapter {

private AuthenticationManager authenticationManager;

@Autowired
public EndpointSecurityConfig(AuthenticationManager authenticationManager) {
   this.authenticationManager = authenticationManager;
}

@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off

  http
    .formLogin()
      .loginPage("/login")
      .usernameParameter("name")
      .loginProcessingUrl("/login.do").permitAll()
    .and()
      .requestMatchers().antMatchers("/login", "/login.do", "/oauth/authorize", "/oauth/confirm_access")
    .and()
      .authorizeRequests().anyRequest().authenticated();

// @formatter:on
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  auth.parentAuthenticationManager(authenticationManager);
}
}

PrincipalRestController

@RestController
public class PrincipalRestController {

@RequestMapping("/principal")
Principal principal(Principal principal) {
return principal;
 }
}

порт шлюза zuul 8765:

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
@EnableOAuth2Sso
@EnableAutoConfiguration
@EnableFeignClients
public class GatewayApplication extends WebSecurityConfigurerAdapter {

public static void main(String[] args) {
    SpringApplication.run(GatewayApplication.class, args);
}

@Override
  protected void configure(HttpSecurity http) throws Exception {
    // @formatter:off
    http
        .logout().and()
        .authorizeRequests()
            .antMatchers("/index.html", "/**/*.js", "/", "/login").permitAll()
            .anyRequest().authenticated()
            .and()
        .csrf()
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    // @formatter:on
  }
}

zuul config:

server:
port: 8765

spring:
  aop:
    proxy-target-class: true

security:
  basic:
    enabled: false

oauth2:
  user:
    password: none
  client:
    accessTokenUri: http://localhost:8899/uaa/oauth/token
    userAuthorizationUri: http://localhost:8899/uaa/oauth/authorize
    clientId: client
    clientSecret: secret
  resource:
    userInfoUri: http://localhost:8899/uaa/principal
    preferTokenInfo: false

zuul:
  routes:
    adminPortal:
      url: http://localhost:4200
      path: /**
    user:
      url: http://localhost:8899/uaa/principal

angular 2 порт приложения 4200 за шлюзом:

услуга

@Injectable()
export class LoginService {
 constructor (private http: Http) {}

 getLoggedInUser() : Observable<LoggedInUser>{

 var authHeader = new Headers();
 authHeader.append( "X-Requested-With", "XMLHttpRequest" );

 return this.http.get("/user",{
   headers: authHeader
 })
 .map((res:Response) => res.json())
 .catch((error:any) => Observable.throw(error.json().error || 'Server error'));

}

logout() : Observable<LoggedInUser>{

var authHeader = new Headers();
authHeader.append( "X-Requested-With", "XMLHttpRequest" );

return this.http.post("/logout",{},{headers: authHeader})
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));

}
}

составная часть

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.sass'],
 providers: [ LoginService ]
})
export class AppComponent {

 loggedInUser: LoggedInUser;

 constructor(
   private loginService: LoginService
  ){
    this.getLoggedInUser();
  }

 getLoggedInUser(){
   // Get all comments
   this.loginService.getLoggedInUser()
   .subscribe(
      loggedInUser => this.loggedInUser = loggedInUser,
     err => {
      console.log(err);
    });
   }

  logout(){
    this.loginService.logout()
   .subscribe(
        loggedInUser => this.loggedInUser = loggedInUser,
        err => {
          console.log(err);
        });
   }

  }

Итак, если я перейду в браузер и открою localhost: 8765 / запрос будет привязан к главной странице angular2, где выполняется вызов getLoggedInUser (). Это перейдет к 'localhost: 8765 / user', потому что на этом этапе пользователь не вошел в систему, этот вызов терпит неудачу с 302, как ожидалось, но затем автоматическое перенаправление для входа в систему также выдает 302, а затем другие вызовы в цепочке выполняются с 302. В этом случае в то же время консольные шоу

XMLHttpRequest не может загрузить http://localhost:8899/uaa/oauth/authorize?client_id=client&redirect_uri=http://localhost:8765/login&response_type=code&state=woE3Yc. Перенаправление с 'http://localhost:8899/uaa/oauth/authorize?client_id=client&redirect_uri=http://localhost:8765/login&response_type=code&state=woE3Yc 'to' http://localhost:8899/uaa/login 'заблокирован политикой CORS: на запрошенном ресурсе отсутствует заголовок' Access-Control-Allow-Origin '. Следовательно, к источнику "http://localhost:8765" не разрешен доступ.

все это показано на изображении ниже:

введите здесь описание изображения

введите здесь описание изображения


person user1048282    schedule 31.01.2017    source источник
comment
Добавьте заголовок, позволяющий получить доступ к другим сайтам.   -  person Roman C    schedule 31.01.2017
comment
Спасибо @RomanC, можно ли дать мне пример?   -  person user1048282    schedule 31.01.2017


Ответы (1)


настройте CORS в приложении Spring: https://spring.io/guides/gs/rest-service-cors/

или ссылку на эту документацию https://spring.io/blog/2015/06/08/cors-support-in-spring-framework#javaconfig

person Tiep Phan    schedule 31.01.2017
comment
Да, я прочитал эту статью и безуспешно добавил код ниже: @Bean public WebMvcConfigurer corsConfigurer () {return new WebMvcConfigurerAdapter () {'@Override' public void addCorsMappings (реестр CorsRegistry) {registry.addMapping (/ **). AllowedOrigins (localhost: 8765); }}; } - person user1048282; 31.01.2017
comment
попробуйте .allowedOrigins("*") или .allowedOrigins("http://localhost:8765") - person Tiep Phan; 31.01.2017
comment
да, извините, я поспешил с моим предыдущим ответом. Я поставил .allowedOrigins ('localhost: 8765'), и теперь я даже попробовал .allowedOrigins (*) та же проблема: / haha ​​github удаляет http :) - person user1048282; 31.01.2017
comment
вы имеете в виду, вы включили CORS на сервере localhost:8899, как я вижу, у вас есть 2 сервера на портах 8899 и 8765 - person Tiep Phan; 31.01.2017
comment
да, я добавил в 8899 сервер oauth ›@Bean public WebMvcConfigurer corsConfigurer () {return new WebMvcConfigurerAdapter () {'@Override' public void addCorsMappings (реестр CorsRegistry) {registry.addMapping (/ **). allowedOrigins (localhost: 8765); }}; } - person user1048282; 31.01.2017
comment
да, ваш класс конфигурации загружен, или вы пытаетесь перезапустить приложение. Я думаю, что включить CORS - это нормально. - person Tiep Phan; 31.01.2017
comment
да, я даже поставил точку останова, чтобы увидеть, загружена ли эта конфигурация, и при запуске точка останова сработала, поэтому я предположил, что она загружена. Мне кажется, может быть что-то еще: / - person user1048282; 31.01.2017