0
votes

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

1
Add a header that allows to access other sites.Roman C
Thanks @RomanC is it possible you could give me an example of doing so ?user1048282

1 Answers