У меня проблемы с заголовками CORS при отправке HTTP-запроса из моего приложения Angular 7 (размещенного на http://localhost:4200) в мое приложение Spring-Boot (размещенного на https://localhost:8924) из Firefox.
У меня в приложении Spring-Boot есть фильтр CORS, который добавлен к моему запросу:
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Content-Type");
response.addIntHeader("Access-Control-Max-Age", 3600);
if ("OPTIONS".equalsIgnoreCase(request.getMethod()))
{
response.setStatus(HttpServletResponse.SC_OK);
}
else
{
filterChain.doFilter(request, response);
}
}
}
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.addFilterBefore(corsFilter(), SessionManagementFilter.class);
http.csrf().disable().
authorizeRequests()
.antMatchers("/api/auth/**","/api/MentorCalendar","/api/user/role/**").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
При отправке запроса консоль Firefox возвращает это сообщение об ошибке:
Запрос перекрестного источника заблокирован: та же политика происхождения запрещает чтение удаленного ресурса в http://localhost:8924/api/auth/signin. (причина: несколько заголовков CORS 'Access-Control-Allow-Origin' не разрешены).
Закомментирование Access-Control-Allow-Origin:
@Component
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
// response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, HEAD");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-With, Authorization, Content-Type");
response.addIntHeader("Access-Control-Max-Age", 3600);
if ("OPTIONS".equalsIgnoreCase(request.getMethod()))
{
response.setStatus(HttpServletResponse.SC_OK);
}
else
{
filterChain.doFilter(request, response);
}
}
}
Возвращает это сообщение об ошибке:
Запрос перекрестного источника заблокирован: та же политика происхождения запрещает чтение удаленного ресурса на http://localhost:8924/api/auth/signin. (причина: отсутствует заголовок CORS «Access-Control-Allow-Origin»).
src / app / home / login.component.ts extract
export class LoginComponent {
constructor(private LoginService: LoginService, private router: Router) {}
login(inputUsername, inputPassword){
this.LoginService.login({username: inputUsername, password: inputPassword})
.subscribe(data => {
localStorage.setItem("jwtToken", data.accessToken);
src /app / home / login.service.ts
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
@Injectable()
export class LoginService {
loginUrl = "http://localhost:8924/api/auth/signin";
constructor( private http: HttpClient ) {}
login(loginCreds: any): Observable<any> {
return this.http.post<any>(this.loginUrl, loginCreds, httpOptions);
}
}
Как это сделатьон response.addHeader («Access-Control-Allow-Origin», «*»);строка устанавливает несколько заголовков, когда они включены, но нет, когда я их удаляю?