Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
spring zuul网关具有oauth2 sso和angular 2 CORS问题_Angular_Spring Security_Spring Cloud_Spring Security Oauth2_Spring Oauth2 - Fatal编程技术网

spring zuul网关具有oauth2 sso和angular 2 CORS问题

spring zuul网关具有oauth2 sso和angular 2 CORS问题,angular,spring-security,spring-cloud,spring-security-oauth2,spring-oauth2,Angular,Spring Security,Spring Cloud,Spring Security Oauth2,Spring Oauth2,嗨,我的微服务sso设置有CORS问题,但我无法找出原因。我的设置: oauth microservice端口8899: @Configuration @Order(-20) public class EndpointSecurityConfig extends WebSecurityConfigurerAdapter { private AuthenticationManager authenticationManager; @Autowired public EndpointSecuri

嗨,我的微服务sso设置有CORS问题,但我无法找出原因。我的设置:

oauth microservice端口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);
}
}
主控制器

@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配置:

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
网关后面的角度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'));

}
}
因此,如果我转到浏览器并打开localhost:8765/request,它将以根目录形式指向执行getLoggedInUser()调用的主angular2页面。这将转到“localhost:8765/user”,因为在此阶段用户未登录。此调用将按预期使用302失败,但自动重定向到登录也会抛出302,然后使用302执行链中的其他调用。此时,控制台显示

无法加载XMLHttpRequest。从“”重定向到“”已被CORS策略阻止:请求的资源上不存在“访问控制允许来源”标头。因此,不允许访问源“”

所有这些都在下图中演示:


在spring应用程序中配置CORS:

或此文档链接

添加允许访问其他网站的标题。谢谢@RomanC。你能给我举个这样做的例子吗?是的,我读了这篇文章,并在下面添加了代码,但运气不好:@Bean public webmvcconfiguer corsConfigurer(){return new WebMvcConfigurerAdapter(){@Override'public void addCorsMappings(CorsRegistry注册表){registry.addMapping(“/**”).AllowedOriginates(“;}}};}尝试
.AllowedOriginates(*”
.AllowedOriginates(“http://localhost:8765“
是的,对不起,我上一次的回答太仓促了,我把“.allowedOrigins(”)放在了上面,现在我甚至试过了。allowedOrigins(“*”)同样的问题:/haha github正在删除http:)您的意思是,您在服务器
localhost:8899
中启用了CORS,正如我看到的,您在8899 oauth服务器中添加的8899和8765端口上有两台服务器>@Bean public WebMvcConfigurer corsConfigurer(){返回新的WebMvcConfigurerAdapter(){'@Override'public void addCorsMappings(CorsRegistry注册表){registry.addMapping(“/**”).AllowedOriginates(“);};}
@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);
        });
   }

  }