spring boot OAuth2无法实现跨域CORS
spring boot 项目集成了OAuth2认证,http请求正常,访问未保护的接口正常,但当使用ajax跨域访问auth保护的接口,就报401,求大神帮忙看下。
@SpringBootApplication
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class App extends SpringBootServletInitializer{
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(App.class);
}
@Bean
public CorsFilter corsFilter() {
final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
final CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowCredentials(true);
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(urlBasedCorsConfigurationSource);
}
public static void main( String[] args ){
SpringApplication.run(App.class, args);
System.out.println( "Rong Server is running..." );
}
}
@Configuration
public class GlobalAuthConfig extends GlobalAuthenticationConfigurerAdapter {
@Autowired
private UserRepository userRepository;
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService());
}
@Bean
public UserDetailsService userDetailsService() {
return (username) -> userRepository.findByUsername(username)
.map(a -> new User(a.username, a.password, a.enabled, a.accountNonExpired, a.credentialsNonExpired,
a.accountNonLocked, AuthorityUtils.createAuthorityList(a.authorities)))
.orElseThrow(() -> new UserNotExistException());
}
}
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
// This is required for password grants, which we specify below as one of the
// {@literal authorizedGrantTypes()}.
@Autowired
AppConfig config;
@Autowired
AuthenticationManagerBuilder authenticationManager;
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints.authenticationManager(new AuthenticationManager() {
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
return authenticationManager.getOrBuild().authenticate(authentication);
}
});
}
// Client settings
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient(config.clientId)
.authorizedGrantTypes("password", "refresh_token")
.authorities("ROLE_USER").scopes("write")
.secret(config.clientSecret);
}
}
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedHeaders("*").allowedMethods("*").allowedOrigins("*");
}
}
@Configuration
@EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
遇到同样的问题,困扰好久了,不知道楼主解决了没?解决麻烦告知一下,不胜感激。
加入@CrossOrigin()在server段
在你的ResourceServer类里加
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
上面的我都试过,不行,看了下源码,security里有个cros方法,我简单测试了下是可以的
http需要这样配置:http.cors().and().csrf().disable();
下面是代码: