繁体   English   中英

Spring API REST 和 Cors 以及 AngularJS

[英]Spring API REST and Cors and AngularJS

我对 Spring Boot 和 Cors 进行了探测 经过一些搜索后,我找到了解决方案( Spring Data Rest 和 Cors以及如何在 Spring Boot + Spring Security 应用程序中配置 CORS? ),我尝试过但不能解决我的问题。 我的 JWT 身份验证代码

 public class AuthenticationFilter extends AbstractAuthenticationProcessingFilter
{
private final Logger log  =  LoggerFactory.getLogger(AuthenticationFilter.class);
private final String tokenHeader = "Authorization";
private final TokenUtils tokenUtils = new TokenUtils();

public AuthenticationFilter()
{
    super("/api/v1/**");
    tokenUtils.expiration = 86400;
    tokenUtils.secret = "papipapo123popo";
}

@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException
{
    String header = httpServletRequest.getHeader(tokenHeader);
    if(header == null || !header.startsWith("Bearer "))
    {
        log.error("Not found JWT token in request headers","Not found header Authorization");
        throw new JwtTokenMissingException("No JWT token found in request headers");
    }
    String token = header.substring(7);
    JwtAuthentication jwtAuthentication = new JwtAuthentication(token);
    boolean isValid = tokenUtils.validateToken(token);
    if(!isValid)
    {
        log.error("JWT token is expired",token);
        throw new JwtTokenExpired("JWT token is expired");
    }
    return this.getAuthenticationManager().authenticate(jwtAuthentication);
}

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException
{
    super.successfulAuthentication(request, response, chain, authResult);
    String token = ((JwtAuthentication)authResult).getToken();
    log.info("Token is authenticated : ",token);
    chain.doFilter(request, response);
}

   @Override
   protected AuthenticationManager getAuthenticationManager()
  {
    return authentication -> (JwtAuthentication) authentication;
  }
}

我的配置安全代码

@Configuration
@EnableWebSecurity
@EnableAutoConfiguration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter
{

@Inject
private EntryPointUnauthorizedHandler entryPointUnauthorizedHandler;

@Inject
private JwtAuthenticationProvider jwtAuthenticationProvider;


@Bean
@Override
public AuthenticationManager authenticationManager() throws Exception
{
    return new ProviderManager(Arrays.asList(jwtAuthenticationProvider));
}

@Bean
public AuthenticationFilter authenticationFilter() throws Exception
{
    AuthenticationFilter authenticationFilter = new AuthenticationFilter();
    authenticationFilter.setAuthenticationManager(authenticationManager());
    authenticationFilter.setAuthenticationSuccessHandler(new EntryPointSuccessHandler());
    return authenticationFilter;
}

@Bean
public FilterRegistrationBean corsFilter()
{
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    config.addAllowedOrigin("*");
    source.registerCorsConfiguration("/**",config);
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new CorsFilter(source));
    filterRegistrationBean.setOrder(0);
    return filterRegistrationBean;
}

@Override
protected void configure(HttpSecurity http) throws Exception
{
    http
        .csrf()
            .disable()
        .exceptionHandling()
            .authenticationEntryPoint(entryPointUnauthorizedHandler)
        .and()
        .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .antMatchers(HttpMethod.POST,"/api/auth").permitAll()
            .anyRequest().authenticated();

    http.addFilterBefore(authenticationFilter(),UsernamePasswordAuthenticationFilter.class);
    http.headers().cacheControl();
}
}

我总是收到错误 401 拒绝访问。 我是 Spring-Boot 的初学者。 你可以帮我。

我通过添加一个实现过滤器的类解决了我的问题。

@Component
public class CorsConfig implements Filter
{

@Override
public void init(FilterConfig filterConfig) throws ServletException
{}

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    String method = request.getMethod();
    if(method.equals("OPTIONS") || method.equals("options"))
    {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        response.setStatus(200);
        filterChain.doFilter(servletRequest, servletResponse);
    }
    else
    {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        filterChain.doFilter(servletRequest, servletResponse);
    }
}

@Override
public void destroy()
{}

}

第一课:

 @Configuration
public class MyConfiguration {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
} 

第二类:

@EnableWebSecurity
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
                .anyRequest().fullyAuthenticated().and().httpBasic().and().csrf().disable();
    }
}

快乐我的朋友

1:创建一个类 WebMvcConfig 扩展 WebMvcConfiguration 并覆盖 addCorsMappings 方法。

2:别忘了做@Configuration注解

 @Configuration
public class WebMvcCofig implements WebMvcConfigurer{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/*")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM