spring boot OAuth2无法实现跨域CORS

spring boot 项目集成了OAuth2认证,http请求正常,访问未保护的接口正常,但当使用ajax跨域访问auth保护的接口,就报401,求大神帮忙看下。

clipboard.png

@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();
    }
}
阅读 15.5k
4 个回答
新手上路,请多包涵

遇到同样的问题,困扰好久了,不知道楼主解决了没?解决麻烦告知一下,不胜感激。

新手上路,请多包涵

加入@CrossOrigin()在server段

新手上路,请多包涵

在你的ResourceServer类里加
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()

上面的我都试过,不行,看了下源码,security里有个cros方法,我简单测试了下是可以的

http需要这样配置:http.cors().and().csrf().disable();

下面是代码:


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        List<String> allowedOrigins = new ArrayList<String>();
        allowedOrigins.add("http://localhost:8000");


        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(allowedOrigins);
        configuration.addAllowedHeader("*");
        configuration.addAllowedMethod("*");
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http
                .formLogin()
               .and()
                   .authorizeRequests()
                   .antMatchers("/try/**").permitAll()
                   .anyRequest().authenticated()
               .and()
                .cors()
               .and()
                    .csrf().disable();
    }


}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题