首页 > spring boot OAuth2无法实现跨域CORS

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();
    }
}

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

【热门文章】
【热门文章】