0

Hi I have CORS issue with my microservices sso setup but I'm failing to figure it out why. My setup:

oauth microservice port 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 gateway port 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 app port 4200 behind gateway:

service

@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

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

  }

So If I go to the browser and open the localhost:8765/ request is rooted to main angular2 page where getLoggedInUser() call is executed. This will go to 'localhost:8765/user' because at this stage user is not logged in this call fails with 302 as expected but then automatic redirection to login throws 302 too and then other calls in the chain are executed with 302. In this same time console shows

XMLHttpRequest cannot load http://localhost:8899/uaa/oauth/authorize?client_id=client&redirect_uri=http://localhost:8765/login&response_type=code&state=woE3Yc. Redirect from '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' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8765' is therefore not allowed access.

all of this is demonstrated in image below:

enter image description here

enter image description here

user1048282
  • 780
  • 1
  • 9
  • 22

1 Answers1

0

config CORS in your spring application: https://spring.io/guides/gs/rest-service-cors/

or this documentation link https://spring.io/blog/2015/06/08/cors-support-in-spring-framework#javaconfig

Tiep Phan
  • 12,386
  • 3
  • 38
  • 41
  • Yes I read this article and I added code below with no luck: @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { '@Override' public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("http://localhost:8765"); } }; } – user1048282 Jan 31 '17 at 10:51
  • try `.allowedOrigins("*")` or `.allowedOrigins("http://localhost:8765")` – Tiep Phan Jan 31 '17 at 10:55
  • yeah sorry rushed my previous answer I did put ".allowedOrigins('http://localhost:8765')" and now I even tried .allowedOrigins("*") this same issue :/ haha github is removing http :) – user1048282 Jan 31 '17 at 11:19
  • you mean, you enabled CORS in server `localhost:8899`, as i see, you have 2 servers at 8899 and 8765 ports – Tiep Phan Jan 31 '17 at 11:23
  • yes I added in 8899 oauth server > @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { '@Override' public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**").allowedOrigins("http://localhost:8765"); } }; } – user1048282 Jan 31 '17 at 11:25
  • huh, did your configure class is loaded, or you try to restart your application. i think enable CORS is fine. – Tiep Phan Jan 31 '17 at 11:50
  • yes I even put the breakpoint to see if this configuration is loaded and on startup the breakpoint had a hit so I assumed it was loaded. It feels to me there may be something else :/ – user1048282 Jan 31 '17 at 11:54