簡體   English   中英

Spring Oauth2 CORS

[英]Spring Oauth2 CORS

我正在嘗試在 Angular 應用程序中調用我的登錄服務,但我遇到了 CORS 錯誤。 我已經在 WebSecurityConfigurerAdapter 上添加了 cors 配置。 我已經嘗試了一些像下面這樣的配置。 郵遞員一切正常。

授權服務器配置器適配器

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

網絡安全配置器適配器

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

瀏覽器嘗試驗證 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;
              }

唯一對我有用的解決方案( Spring 安全性,啟用 Oauth2 時出現 cors 錯誤

@Component @Order(Ordered.HIGHEST_PRECEDENCE) @WebFilter("/*") //TODO 在可能的情況下排除 API 端點 public class CorsFilter 實現 Filter {

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

}

我還需要從擴展 WebSecurityConfigurerAdapter 和 ResourceServerConfigurerAdapter 的類的配置方法中刪除 http.cors()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM