Я настроил крест, как показано ниже, для приложения с пружинной загрузкой и защитой пружины. Приложение Spring-boot с пружинной защитой вместе с токеном jwt.
Я использую API-интерфейсы с другим доменом, поэтому я использую перекрестное происхождение на всех контроллерах.
Все вызовы API, которые не являются Требуемый токен авторизации (JWT) прекрасно работает с приведенными ниже конфигурациями. Но вызовы API, с которыми требуется токен jwt, терпят неудачу с ошибкой ниже.
Я пытаюсь добавить фильтры, но они не работают должным образом. Может ли кто-нибудь помочь мне здесь.
спасибо.
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Import(SecurityProblemSupport.class)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final AuthenticationManagerBuilder authenticationManagerBuilder;
private final DomainUserDetailsService userDetailsService;
private final TokenProvider tokenProvider;
// private final CorsFilter corsFilter;
private final SecurityProblemSupport problemSupport;
@Autowired
public SecurityConfig(AuthenticationManagerBuilder authenticationManagerBuilder, DomainUserDetailsService userDetailsService, TokenProvider tokenProvider, SecurityProblemSupport problemSupport) {
this.authenticationManagerBuilder = authenticationManagerBuilder;
this.userDetailsService = userDetailsService;
this.tokenProvider = tokenProvider;
// this.corsFilter = corsFilter;
this.problemSupport = problemSupport;
}
@PostConstruct
public void init() {
try {
authenticationManagerBuilder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
} catch (Exception e) {
throw new BeanInitializationException("Security configuration failed", e);
}
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().disable().csrf().ignoringAntMatchers("/api/**", "/reports/**", "/utils/**").and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()
.antMatchers("/", "/*.html", "/**/*.js", "/**/*.png", "/**/*.css", "/**/*.woff2", "/**/*.woff",
"/**/*.ico", "/**/*.ttf", "/**/*.jpg")
.permitAll().antMatchers("/api/auth/**", "/api/util/**", "/api/feed/getJobs", // feed can be seen
// without auth
"/api/user/user-details/**", // user details can be seen without auth
"/v2/api-docs/**", "/actuators/**", "/api-docs/**", "/utils/**")
.permitAll().anyRequest().authenticated().and().apply(securityConfigurerAdapter()).and()
// handle an authorized attempts
.exceptionHandling()
.authenticationEntryPoint((req, rsp, e) -> rsp.sendError(HttpServletResponse.SC_UNAUTHORIZED));
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
private JWTConfigurer securityConfigurerAdapter() {
return new JWTConfigurer(tokenProvider, userDetailsService);
}
GET, POST, PUT, DELETE API-вызовы без jwt работает.
API-вызовы с JWT не работают, получая ниже ошибка
Access to XMLHttpRequest at 'http://localhost:8082/api/feed/posted-by-me' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Может кто-нибудь сказать, что я делаю неправильно ??
Я использую Angular 9 на входе для вызова Apis.