Политика CORS с загрузкой Spring и AngularJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Политика CORS с загрузкой Spring и Angular

Сообщение Anonymous »

Я разрабатываю приложение Angular, которое должно входить в приложение SpringBoot. Бэкэнд структурирован так, чтобы выполнять аутентификацию с использованием имени пользователя и пароля и при аутентификации возвращать токен JWT во внешний интерфейс.
Эта структура работает, когда я использую почтальона, как показано ниже.
введите здесь описание изображения
введите здесь описание изображения
Однако, когда я использую свое приложение для выполнения этих запросов, генерируется ошибка политики CORS.
введите описание изображения. здесь
Вот мой угловой компонент: import { Component } from '@angular/core';

Код: Выделить всё

import { FormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

@Component({
selector: 'app-loginscreen',
templateUrl: './loginscreen.component.html',
styleUrls: ['./loginscreen.component.css']
})
export class LoginscreenComponent {
constructor(private httpClient: HttpClient) { }
public inputUsername: string = "";
public inputPassword: string = "";

login() {
// preparar requisição http
// Suponhamos que você tenha uma URL e os dados de login
const url = 'http://localhost:8080/auth/login';
const dadosDeLogin = {
username: this.inputUsername,
password: this.inputPassword
};
const headers = { 'content-type': 'application/json'}

this.httpClient.post(url, dadosDeLogin, { headers })
.subscribe(data => {
console.log(data);
})

}

}
Вот мой класс SecurityFilter:

Код: Выделить всё

@Component
public class SecurityFilter extends OncePerRequestFilter {
@Autowired
TokenService tokenService;
@Autowired
AdministratorRepository administratorRepository;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
var token = this.recoverToken(request);
if(token != null){
var login = tokenService.validateToken(token);
UserDetails user = administratorRepository.findByUsername(login);

// Requests CORS
response.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");

var authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}

private String recoverToken(HttpServletRequest request) {
var authHeader = request.getHeader("Authorization");
if(authHeader == null) return null;
return authHeader.replace("Bearer ", "");
}
}
А вот мой класс SecurityConfig:

Код: Выделить всё

@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Autowired
SecurityFilter securityFilter;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
return httpSecurity
.csrf(csrf -> csrf.disable())
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(authorize -> authorize
.requestMatchers(AntPathRequestMatcher.antMatcher(HttpMethod.POST, "/auth/login")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher(HttpMethod.POST, "/auth/register")).permitAll()
.requestMatchers(AntPathRequestMatcher.antMatcher(HttpMethod.POST, "/users")).hasRole("ADMIN")
.anyRequest().authenticated()
)
.addFilterBefore(securityFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}

@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}

@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
Я попробовал несколько способов устранить эту ошибку, установив политику CORS в своем бэкэнде, но ничего не помогло. Можете ли вы мне помочь?
Я попробовал включить перекрестное происхождение через свой сервер.

Подробнее здесь: https://stackoverflow.com/questions/773 ... nd-angular
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»