oauth认证无法跨域访问

发布于 2022-09-03 07:28:51 字数 2464 浏览 20 评论 0

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

报错:

clipboard.png

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最丧也最甜 2022-09-10 07:28:51

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

图片描述

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文