BE전문가 프로젝트
4-3 Authentication(인증) - CorsFilter(선택사항) 본문
0. 프로젝트 소개(Spring Security) 및 Security에 대하여
1. User Entity 생성(Spring Security)
2. User 회원가입 (Spring Secureity)
3.Jwt의 사용 이유 (Spring Security)
4. Authorization(인증)
- 4-0 Authorization(인증) - 프로세스 설명
- 4-1 Authentication(인증) - UserDetails, UserDetailsService 및 JwtService 생성
- 4-2 Authentication(인증) - UsernamePasswordAuthenticationfilter 생성
- 4-3 Authentication(인증) - CorsFilter(선택사항)
- 4-4 Authentication(인증) - SecurityConfig
5. Authorization(인가)
- 5-1 Authorization(인가) - Jwt 인가 관련 에러 처리
- 5-2 Authorization(인가) - Jwt 인가 서비스 로직 추가
- 5-3 Authorization(인가) - AuthorizationFilter 생성
- 5-4 Authorization(인가) - SecurityConfig에 인가 관련 method 추가
6. OAuth
Cors(Cross-Origin Resource Sharing)
url의 구조를 살펴보면 다음과 같은 형식을 띄고 있다.
Cross-Origin Resource Sharing을 직역하면 교차 출처(origin) 리소스 공유라고 한다.
따라서 서로 orgin이 다른 리소스를 공유하는 통신을 의미하는데 여기서 origin은 프로토콜, 호스트, 포트까지를 의미한다.
http에서는 Corss-Origin 정책을 따르기 때문에 link를 통해 다른 Origin 소스에 접근할 수가 있다.
예를 들어 BootStarp을 이용할 때 http에 link태그를 통해 접근할 수 있다는 것을 보면 알 수 있다.
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
하지만 script 태그 내에서는 보안상의 이유로 Same-Origin 정책을 따르기 때문에 다음과 같은 오류를 볼 수 있을 것이다.
Access to fetch at 'url' from origin 'url2' has been blocked by CORS policy : No 'Access-Control-Allow-Origin' header is present on the requested rescource. If an opaque respose serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
이를 통해 살펴보면 script를 통해 서로 다른 Origin의 서버 접근에 대한 요청을 거부한다는 것을 알 수 있다.
따라서 별도의 API를 만들어 script를 통해 통신하고 싶다면 아래의 필터를 만들어 적용해줘야 한다.
CorsFilter 생성(선택사항)
/**
* @package com.example.spring_security.config.security.config
* @enum CorsConfig
* @author 최원호
* @date 2023.06.22
* version 1.0
*/
@Configuration
public class CorsConfig {
/**
* @brief CORS 차단을 해제하고 JWT 방식으로만 검증할 것임으로 생성
* @return CorsFilter
*/
@Bean
public CorsFilter corsFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true); //json 서버 응답을 자바 스크립트에서 처리할 수 있게 해줌
config.addAllowedOrigin("http://localhost:8080"); //모든 IP에 응답을 허용
config.addAllowedHeader("*"); //모든 Http Header에 허용
config.addAllowedMethod("*"); //모든 Http METHOD에 허용
config.addExposedHeader(JwtProperties.ACCESS_TOKEN_HEADER);
config.addExposedHeader(JwtProperties.REFRESH_TOKEN_HEADER);
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
}
'SpringBoot Security' 카테고리의 다른 글
5-1 Authorization(인가) - Jwt 인가 관련 에러 처리 (0) | 2023.07.11 |
---|---|
4-4 Authentication(인증) - SecurityConfig (0) | 2023.07.09 |
4-2 Authentication(인증) - UsernamePasswordAuthenticationfilter 생성 (0) | 2023.07.09 |
4-1 Authentication(인증) - UserDetails, UserDetailsService 및 JwtService 생성 (0) | 2023.07.09 |
4-0 Authorization(인증) - 프로세스 설명 (0) | 2023.07.08 |