Привет, у меня проблема 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" не разрешен доступ.
все это показано на изображении ниже: