특정 인증키를 사용하여 접근을 하도록 구현
APIKeyAuthFilter
import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter
import javax.servlet.http.HttpServletRequest
class APIKeyAuthFilter(private val principalRequestHeader: String) : AbstractPreAuthenticatedProcessingFilter() {
override fun getPreAuthenticatedPrincipal(request: HttpServletRequest): Any {
return request.getHeader(principalRequestHeader)
}
override fun getPreAuthenticatedCredentials(request: HttpServletRequest): Any {
return "N/A"
}
}
SecurityConfiguration
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;;
@Configuration
@EnableWebSecurity
class SecurityConfiguratio:WebSecurityConfigurerAdapter() {
@Value("${appname.http.auth-token-header.name}")
private lateinit var principalRequestHeader: String
@Value("${appname.http.auth-token}")
private lateinit var principalRequestValue: String
override fun configure(http: HttpSecurity) {
val filter = APIKeyAuthFilter(principalRequestHeader)
filter.setAuthenticationManager { authentication: Authentication ->
val principal = authentication.principal as String
if (principalRequestValue != principal) throw InvalidAuthKeyException("The API key was not found or not the expected value.")
authentication.isAuthenticated = true
authentication
}
http.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(filter)
.authorizeRequests()
.anyRequest()
.authenticated()
.and().formLogin().disable()
}
}
application.yml 설정
appname:
http:
auth-token-header:
name: Internal-Key
auth-token: Key값
auth-token-header.name는 인증키 값이 포함될 헤더의 파라미터 이름을 지정해주고
auth-token에 인증키 값을 넣는다
Postman으로 테스트 시 아래와 같이 요청하면 된다
인증키가 유효하지 않을 경우ControllerAdvice 등을 이용하여 RESTAPI 성격에 맞게 json으로 리턴을 해줄 수 있도록 작성
추가로 SecurityConfiguration에 다른 필터도 적용이 되어있다면...
http.csrf().disable()
.authorizeRequests()
.antMatchers("/register", "/login").permitAll() //인증 없이 무조건 접근 허용
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().antMatcher(apikey필터 적용할 경로 추가).addFilter(filter)
.addFilterBefore(JwtFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter::class.java)
Reference
반응형
'Kotlin' 카테고리의 다른 글
QueryDSL select절에 subQuery 조회 (0) | 2022.12.13 |
---|---|
[QueryDSL] 동적 쿼리 작성하기/BooleanBuilder, BooleanExpression (0) | 2022.12.07 |
[Spring Boot] Interceptor로 토큰 검증 적용 (0) | 2022.11.10 |
[Spring Boot] AOP 적용하기 (0) | 2022.11.01 |
[Kotlin]CrossOrigin Annotation 여러 origin 사용 (0) | 2022.10.31 |
댓글