我正在使用Angular和SpringBoot处理Oauth并且收到CORS错误:
无法加载http:// localhost:8080 / login:从'http:// localhost:8080 / login'重定向到'https:// Hostname / auth / oauth / v2 / authorize?client_id = ef9a1536-6533-483f -9c78-d7082bdd0b3f&redirect_uri = http:// localhost:8080 / login&response_type = code&scope = openid&state = FlbM4r'已被CORS策略阻止:请求的资源上没有“Access-Control-Allow-Origin”标头 . 因此不允许来源'http:// localhost:4200'访问 .
这是我的Spring代码:
@SpringBootApplication
@EnableOAuth2Sso
@RestController
public class OAuthClientApplication extends WebSecurityConfigurerAdapter{
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:4200")
public Principal user(Principal principal) {
logger.info("inside USER method "+principal);
//Custom code to check details in principal object
Map<String, String> details = new LinkedHashMap<>();
if (principal != null) {
OAuth2Authentication oAuth2Authentication = (OAuth2Authentication) principal;
Authentication authentication = oAuth2Authentication.getUserAuthentication();
details = (Map<String, String>) authentication.getDetails();
logger.info("details = " + details); // id, email, name, link etc.
/*Map<String, String> map = new LinkedHashMap<>();
map.put("email", details.get("email"));
return map;*/
}
return principal;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/**")
.authorizeRequests()
.antMatchers("/", "/login**", "/webjars/**", "/error**")
.permitAll()
.anyRequest()
.authenticated()
.and().logout().logoutSuccessUrl("/").permitAll()
.and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
@Bean
@SuppressWarnings("unchecked")
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:4200");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return source;
}
public static void main(String[] args) {
SpringApplication.run(OAuthClientApplication.class, args);
}
}
如果我在这里做错了,请告诉我 .