我有Spring启动休息应用程序 . 最近我使用JsonWebToken实现了用户身份验证 .
当我使用邮递员测试它时,一切似乎都工作正常,但是当从Angular应用程序调用其余部分时,我得到了错误,引用了cors:
对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-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
{
}
}
我的登录控制器有一个映射“/ token”,所有其他控制器都映射为“/ rest / **”有趣的是调用“/ token”控制器工作正常...它返回令牌和用户详细信息 . 服务器响应包含:
-
access-control-allow-credentials→true
-
access-control-allow-origin→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 header http://localhost:4200和http://localhost:4200中有两个值
任何人都有任何帮助:D?