반응형
문제
로그인 기능을 구현하기 위해 스프링 시큐리티를 사용하기로 했다. 스프링 시큐리티를 적용하고 난 후에 기존에 되던 기능들이 안되더라. 왜지? 개발자도구 콘솔에서 에러 내용을 보니 news가 login으로 리다이렉트 되고 있었다.
Access to XMLHttpRequest at 'http://localhost:5000/login'
(redirected from 'http://localhost:3000/api/news')
from origin 'http://localhost:3000' has been blocked
by CORS policy: No 'Access-Control-Allow-Origin'
header is present on the requested resource.
해결
스프링 시큐리티 문제인 걸 파악했으니 이제 스프링 시큐리티 클래스를 수정해주면 된다.
/api/news에 대한 요청을 인증 없이 허가하는 코드를 추가해주면 해결된다.
.requestMatchers("/api/**").permitAll()
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/api/news").permitAll()
.anyRequest().authenticated() // 모든 요청에 대해 인증 필요
)
.formLogin(formLogin -> formLogin // 기본 폼 로그인 설정
.loginPage("/login") // 커스텀 로그인 페이지 설정 (옵션)
.permitAll()
)
.logout(logout -> logout
.logoutUrl("/api/auth/logout") // 로그아웃 URL 설정
.invalidateHttpSession(true) // 세션 무효화
.deleteCookies("JSESSIONID") // 쿠키 삭제
.permitAll()
);
return http.build();
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
반응형
'프로그래밍' 카테고리의 다른 글
[GitHub] 커밋 되돌리기 (롤백) (0) | 2024.07.10 |
---|---|
[GitHub] fatal: refusing to merge unrelated histories (0) | 2024.07.02 |
[Spring] sts4 사용 중 resources 폴더가 없어졌을 때 (0) | 2024.07.01 |
[GitHub] rejected non-fast-forward 에러 간단 해결 방법 (0) | 2024.06.27 |
[Spring Boot] bean 에러 해결 방법 AppConfig 클래스 생성 (0) | 2024.06.24 |
댓글