java - Spring API REST 和 Cors 以及 AngularJS

标签 java spring rest spring-security spring-boot

我对 Spring Boot 和 Cors 有疑问 经过一番搜索后,我找到了解决方案( Spring Data Rest and CorsHow to configure CORS in a Spring Boot + Spring Security application? ),我尝试过但它不能解决我的问题。 我的 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 的初学者。 你可以帮助我。

最佳答案

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

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

}

关于java - Spring API REST 和 Cors 以及 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39977307/

相关文章:

java - 如何区分设计模式和标准多态性

spring - 了解 Spring MVC 中的上下文

php - 使用 Postman 通过原始 JSON 发送 POST 数据

java - Slf4j 记录器的模式

java - 使用配置设置连接超时

rest - 如何使用apollo客户端发出休息后请求?

git - 我需要从 GitHub 收集关于我们项目的评论统计信息

java - 为什么我不能只比较两个对象的 hashCode 来确定它们是否相等?

java - 动态二维数组可以实现 Java.Collection.size() 方法吗?

java - GridBagLayout - 意外添加/和更改间距