spring boot OAuth2无法实现跨域CORS

发布于 2022-09-03 09:46:27 字数 3856 浏览 22 评论 0

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

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

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

发布评论

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

评论(4

故事未完 2022-09-10 09:46:27

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

满栀 2022-09-10 09:46:27

加入@CrossOrigin()在server段

放血 2022-09-10 09:46:27

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

牵强ㄟ 2022-09-10 09:46:27

上面的我都试过,不行,看了下源码,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();
    }


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