首页 > oauth认证无法跨域访问

oauth认证无法跨域访问

在spring boot项目中遇到跨域访问问题,项目使用了OAuth2.0认证,现在调用接口时遇到了跨域访问的问题。在filter中配置了允许跨域访问,访问不需要token的接口时一切正常,但被OAuth保护的资源就无法通过ajax跨域访问,我的分析是,被oauth保护的接口首先被oauth系统拦截,此时还未进行到filter,所以是不允许跨域访问的,而不允许跨域,被添加到http请求头部无法被oauth系统获取,所以请求无法通过。

报错:

WebConfig:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {        registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET","POST","HEAD","OPTIONS","PUT","DELETE").allowedHeaders("Content-Type","X-Requested-With","accept","Origin","Access-Control-Request-Method","Access-Control-Request-Headers","Authorization").allowCredentials(true);
    }
}

OAuth2Config:

@Configuration
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);
    }
}

ajax:

$.ajax({
        type : "GET",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "bearer xxxxx");
        },
        url : xxx,
        dataType:'json',  
        success : function(data) {
            alert(data);
        },
        headers: {
            "Authorization":"bearer xxxxx"
        }
    });

你这个在哪里弄的 , 我是按照 spring-security-oauth-master 这个源码里面的例子弄的,可以去github下载。

这个目录下面有例子基本上都可以复制出来运行

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