首页 > 解决方案 > Spring Oauth2 CORS

问题描述

我试图在 Angular 应用程序中调用我的登录服务,但我遇到了 CORS 错误。我已经在 WebSecurityConfigurerAdapter 上添加了 cors 配置。我已经尝试了一些类似下面的配置。邮递员一切正常。

AuthorizationServerConfigurerAdapter

            import java.util.Arrays;
            import java.util.Collections;
            import java.util.List;
            import javax.servlet.http.HttpServletRequest;
            import javax.servlet.http.HttpServletResponse;
            import javax.sql.DataSource;
            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.beans.factory.annotation.Qualifier;
            import org.springframework.context.annotation.Bean;
            import org.springframework.context.annotation.Configuration;
            import org.springframework.security.authentication.AuthenticationManager;
            import org.springframework.security.core.userdetails.UserDetailsService;
            import org.springframework.security.crypto.password.PasswordEncoder;
            import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
            import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
            import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
            import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
            import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
            import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
            import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
            import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
            import org.springframework.security.oauth2.provider.token.TokenEnhancer;
            import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
            import org.springframework.security.oauth2.provider.token.TokenStore;
            import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
            import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
            import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
            import org.springframework.web.cors.CorsConfiguration;
            import org.springframework.web.cors.CorsConfigurationSource;
            import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
            import org.springframework.web.servlet.config.annotation.CorsRegistry;
            import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

            @Configuration
            @EnableAuthorizationServer
            public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {

              @Autowired
              @Qualifier("dataSource")
              private DataSource dataSource;

              @Autowired private AuthenticationManager authenticationManager;
              @Autowired private UserDetailsService userDetailsService;
              @Autowired private PasswordEncoder oauthClientPasswordEncoder;


              @Bean
              JwtAccessTokenConverter accessTokenConverter() {
                JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
                ((DefaultAccessTokenConverter) converter.getAccessTokenConverter())
                    .setUserTokenConverter(userAuthenticationConverter());

                return converter;
              }

              @Bean
              public TokenEnhancer tokenEnhancer() {
                return new CustomTokenEnhancer();
              }

              @Bean
              public TokenStore tokenStore() {
                return new JwtTokenStore(accessTokenConverter());
              }

              @Bean
              public OAuth2AccessDeniedHandler oauthAccessDeniedHandler() {
                return new OAuth2AccessDeniedHandler();
              }

              @Override
              public void configure(AuthorizationServerSecurityConfigurer oauthServer) {

                oauthServer
                    .tokenKeyAccess("permitAll()")
                    .checkTokenAccess("isAuthenticated()")
                    .passwordEncoder(oauthClientPasswordEncoder);
              }

              @Override
              public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
                clients.jdbc(dataSource);
              }

              @Bean
              public UserAuthenticationConverter userAuthenticationConverter() {
                DefaultUserAuthenticationConverter defaultUserAuthenticationConverter =
                    new DefaultUserAuthenticationConverter();
                defaultUserAuthenticationConverter.setUserDetailsService(userDetailsService);
                return defaultUserAuthenticationConverter;
              }


              @Override
              public void configure(final AuthorizationServerEndpointsConfigurer endpoints) {
                TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
                tokenEnhancerChain.setTokenEnhancers(
                    List.of(new CustomTokenEnhancer(), accessTokenConverter()));


                endpoints
                    .accessTokenConverter(accessTokenConverter())
                    .userDetailsService(userDetailsService)
                    .authenticationManager(authenticationManager)
                    .tokenEnhancer(tokenEnhancerChain);
              }

            }

资源服务器配置适配器

            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.oauth2.config.annotation.web.configuration.EnableResourceServer;
            import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
            import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
            import org.springframework.web.cors.CorsConfiguration;
            import org.springframework.web.cors.CorsConfigurationSource;
            import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

            import java.util.Arrays;

            @Configuration
            @EnableResourceServer
            public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter {
              private static final String SECURED_PATTERN = "/secured/**";
              private static final String SECURED_READ_SCOPE = "#oauth2.hasScope('read')";
              private static final String SECURED_WRITE_SCOPE = "#oauth2.hasScope('write')";

              @Override
              public void configure(ResourceServerSecurityConfigurer resources) {
                resources.resourceId("resource-server-rest-api").stateless(false);
              }

              @Override
              public void configure(HttpSecurity http) throws Exception {

                http.cors().and().antMatcher("/api/**")
                        .authorizeRequests()
                        .antMatchers("/**", "/login**", "/error**", "/api/auth/**")
                        .permitAll()
                ;
                http.authorizeRequests().antMatchers("/api/**").authenticated();

              }
              @Bean
              CorsConfigurationSource corsConfigurationSource() {
                CorsConfiguration configuration = new CorsConfiguration();
                configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200/"));
                configuration.setAllowedMethods(Arrays.asList("GET","POST"));
                UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
                source.registerCorsConfiguration("/**", configuration);
                return source;
              }
            }

WebSecurityConfigurerAdapter

            import org.springframework.beans.factory.annotation.Autowired;
            import org.springframework.context.annotation.Bean;
            import org.springframework.context.annotation.Configuration;
            import org.springframework.security.authentication.AuthenticationManager;
            import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
            import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
            import org.springframework.security.config.annotation.web.builders.HttpSecurity;
            import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
            import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
            import org.springframework.security.core.userdetails.UserDetailsService;
            import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
            import org.springframework.security.crypto.password.PasswordEncoder;

            @Configuration
            @EnableWebSecurity
            @EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
            public class Oauth2WebSecurityConfig extends WebSecurityConfigurerAdapter {

              @Autowired private UserDetailsService userDetailsService;
              @Autowired private PasswordEncoder userPasswordEncoder;

              @Override
              @Bean
              public AuthenticationManager authenticationManagerBean() throws Exception {
                return super.authenticationManagerBean();
              }

              @Override
              protected void configure(AuthenticationManagerBuilder auth) throws Exception {
                auth.userDetailsService(userDetailsService).passwordEncoder(userPasswordEncoder);
              }


              @Override
              protected void configure(HttpSecurity http) throws Exception {


                http.cors().and().antMatcher("/**")
                    .authorizeRequests()
                    .antMatchers("/**", "/login**", "/error**", "/api/auth/**")
                    .permitAll()
                ;

                http.cors().and()
                        .formLogin();
            ;
              }

              @Bean
              public BCryptPasswordEncoder passwordEncoder() {
                return new BCryptPasswordEncoder();
              }
            }

标签: springspring-bootspring-securityspring-security-oauth2

解决方案


浏览器尝试验证 CORS 的第一步是发送选项方法,因此您还应该启用 OPTIONS 方法,您的 cors 配置

@Bean
              CorsConfigurationSource corsConfigurationSource() {
                CorsConfiguration configuration = new CorsConfiguration();
                configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200/"));
                configuration.setAllowedMethods(Arrays.asList("GET","POST","OPTIONS"));
                UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
                source.registerCorsConfiguration("/**", configuration);
                return source;
              }

推荐阅读