CORS Origin问题 - Spring Boot& Angular 4

时间:2018-05-20 14:50:46

标签: angular spring-boot spring-security cors jwt

我目前正在 Angular 4 FrontEnd App Spring Boot后端应用之间进行JWT身份验证,服务器端的所有功能都可以解决我遇到的问题身份验证级别如下。

enter image description here

在我获得 200 OK 状态后,我的登录请求已成功处理,如下图所示。

enter image description here

低于我用于安全应用程序和登录处理的配置。

    public class JWTAuthorizationFiler extends OncePerRequestFilter {

        @SuppressWarnings("unchecked")
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
                throws ServletException, IOException {

            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, "
                    + "Access-Control-Request-Method, Access-Control-Request-Headers, authorization");
            response.addHeader("Access-Control-Expose-Headers",
                    "Access-Control-Allow-Origin, Access-Control-Allow-Credentials, authorization");

            if (request.getMethod().equals("OPTIONS")) {
                response.setStatus(HttpServletResponse.SC_OK);
            }

            String jwt = request.getHeader(SecurityConstants.HEADER_STRING);
            if (jwt == null || !jwt.startsWith(SecurityConstants.TOKEN_PREFIX)) {
                filterChain.doFilter(request, response);
                return;
            }

            Claims claims = Jwts.parser().setSigningKey(SecurityConstants.SECRET)
                    .parseClaimsJws(jwt.replace(SecurityConstants.TOKEN_PREFIX, "")).getBody();

            String username = claims.getSubject();
            ArrayList<Map<String, String>> roles = (ArrayList<Map<String, String>>) claims.get("roles");

            Collection<GrantedAuthority> authorities = new ArrayList<>();
            roles.forEach(r -> {
                authorities.add(new SimpleGrantedAuthority(r.get("authority")));
            });

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,
                    null, authorities);

            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            filterChain.doFilter(request, response);
        }
    }



    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private UserDetailsService userDetailsService;
        @Autowired
        private BCryptPasswordEncoder bCyptPasswordEncoder;

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

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable();
            http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

            // http.formLogin();
            http.authorizeRequests().antMatchers("/login/**", "/register/**", "/paramsApi/**").permitAll();
            http.authorizeRequests().antMatchers(HttpMethod.POST, "/studentResource/**").hasAuthority("ADMIN");
            http.authorizeRequests().antMatchers(HttpMethod.GET, "/studentResource/**").hasAuthority("ADMIN");
            http.authorizeRequests().anyRequest().authenticated();
            http.addFilter(new JWTAuthenticationFilter(authenticationManager()));
            http.addFilterBefore(new JWTAuthorizationFiler(), UsernamePasswordAuthenticationFilter.class);
        }
    }

我认为 JWTAuthorizationFilter.java 是此次发布的主要原因,请真心感谢此问题的任何解决方案。

1 个答案:

答案 0 :(得分:0)

configure课程的SecurityConfig方法中,你必须像这样启用 CORS

http.cors().and() ...//continue the rest of the configuration..

通过定义http.cors(),它默认使用名称为

的bean

corsConfigurationSource 在这种情况下,您还必须在SecurityConfig类中定义一个bean,它将保留CORS配置。

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

您可以使用WebMvcConfigureAdapter类来启用CORS 以及

    @Configuration
    @EnableWebMvc
    public class WebConfig extends WebMvcConfigurerAdapter {

        @Override
        public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
        .allowedOrigins("your url or just add * ")
        .allowedMethods("PUT", "DELETE")
            .allowedHeaders("header1", "header2", "header3")
        .exposedHeaders("header1", "header2")
        .allowCredentials(false).maxAge(3600);
        }

    }

如果像allowedMethods,allowedHeaders和exposedHeaders那样删除不必要的方法,则可能没有必要进行完整配置。

了解更多信息 https://spring.io/blog/2015/06/08/cors-support-in-spring-framework&amp; https://docs.spring.io/spring-security/site/docs/current/reference/html/cors.html