В настоящее время я работаю над аутентификацией JWT между Angular 4 FrontEnd приложение и Бэкэнд-приложение Spring Boot. Все на стороне сервера работает нормально, проблема, которую я получаю на уровне аутентификации, заключается в следующем.
Это происходит после того, как я получаю статус 200 ОК, что мой запрос на вход был успешно обработан, как показано на рисунке ниже.
Внизу под моей конфигурацией, которую я использовал для приложения безопасности и обработки входа в систему.
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 является основной причиной этой проблемы, буду очень благодарен за любое решение этой проблемы.





в методе configure в классе SecurityConfig вы должны включить CORS следующим образом
http.cors().and() ...//continue the rest of the configuration..
определяя http.cors(), он по умолчанию будет использовать bean-компонент по имени
corsConfigurationSource, в этом случае вы также должны определить bean-компонент внутри класса SecurityConfig, который будет содержать конфигурацию 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 и visibleHeaders.
для получения дополнительной информации пройдите https://spring.io/blog/2015/06/08/cors-support-in-spring-framework & https://docs.spring.io/spring-security/site/docs/current/reference/html/cors.html