【发布时间】:2019-01-09 03:29:36
【问题描述】:
我有 Spring Boot Rest 应用程序。 最近我使用 JsonWebToken 实现了用户认证。
当我使用邮递员对其进行测试时,一切似乎都运行良好, 但是当从 Angular 应用程序调用其余部分时,我得到了错误 引用cors:
对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:4200' 不允许访问。响应的 HTTP 状态代码为 403。
这是我的代码:
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthFilter authFilter;
@Autowired
private JwtAuthenticationProvider authenticationProvider;
@Autowired
private JwtAuthenticationEntryPoint authenticationEntryPoint;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//http.csrf().ignoringAntMatchers("/token");
http.csrf().disable();
http.cors().and().authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers("/token").permitAll()
.antMatchers("/rest/**").authenticated()
.and()
.addFilterBefore(authFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint);
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("GET","POST","OPTIONS","PUT","DELETE"));
configuration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/rest/**", configuration);
return source;
}
}
JwtAuthFilter:
@Component
public class JwtAuthFilter implements Filter
{
@Override
public void doFilter(ServletRequest request, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
HttpServletRequest servletRequest = (HttpServletRequest) request;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String authorization = servletRequest.getHeader("Authorization");
String origin = servletRequest.getHeader("Origin");
if (authorization != null)
{
JwtAuthToken token = new JwtAuthToken(authorization.replaceAll("Bearer ", ""));
SecurityContextHolder.getContext().setAuthentication(token);
}
filterChain.doFilter(servletRequest, response);
}
@Override
public void destroy()
{
}
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
}
}
我的登录Controller有一个映射“/token”,其他所有控制器都映射为“/rest/**” 有趣的是,调用“/token”控制器工作正常……它返回令牌和用户详细信息。服务器响应包含:
- 访问控制允许凭据 →true
- 访问控制允许来源→http://localhost:4200
但是当我调用任何其他控制器时......例如“/rest/task/all”我收到错误并且没有 access-control-allow-credentials 和 access-control-allow-origin 标头。
当我改变时
source.registerCorsConfiguration("/rest/**", configuration);
到
source.registerCorsConfiguration("/**", configuration);
我收到错误消息,我在 access-control-allow-origin 标头中有两个值 http://localhost:4200 和 http://localhost:4200
任何人都可以提供任何帮助:D?
【问题讨论】:
标签: java rest spring-boot cors