当前位置: 首页 > 知识库问答 >
问题:

SpringOauth2 CORS

富念
2023-03-14

我试图在Angular应用程序中调用我的登录服务,但我遇到了CORS错误。我已经在WebSecurity配置适配器上添加了cors配置。我已经尝试了下面的一些配置。邮递员一切都很好。

授权服务器配置RADAPTER

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

            }

资源服务器配置RADAPTER

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

Web安全配置r适配器

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

共有2个答案

咸弘雅
2023-03-14

唯一适合我的解决方案(Spring Security性,启用Oauth2时出现cors错误)

@组件@顺序(已排序。最高\u优先级)@WebFilter(“/*”)//TODO尽可能排除APIendpoint公共类CorsFilter实现筛选器{

public CorsFilter() {
}

@Override
public void init(FilterConfig fc) {
}

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
    System.out.println("doFilter");
    HttpServletResponse response = (HttpServletResponse) resp;
    HttpServletRequest request = (HttpServletRequest) req;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
    response.setHeader("Access-Control-Max-Age", "3600");
    response
            .setHeader("Access-Control-Allow-Headers", "Origin, origin, x-requested-with, authorization, " +
                    "Content-Type, Authorization, credential, X-XSRF-TOKEN");

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        chain.doFilter(req, resp);
    }
}

@Override
public void destroy() {
}

}

我还需要从扩展WebSecurityConfigrerAdapter和ResourceServerConfigrerAdapter的类中删除配置方法中的http.cors()。

沙岳
2023-03-14

浏览器尝试验证CORS的第一步是发送选项方法,因此还应启用选项方法,即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;
              }
 类似资料:

相关问答

相关文章

相关阅读