Untitled
unknown
plain_text
2 years ago
2.7 kB
1
Indexable
Never
import jakarta.servlet.FilterChain import jakarta.servlet.http.HttpServletRequest import jakarta.servlet.http.HttpServletResponse import org.springframework.boot.test.context.TestConfiguration import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Primary import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.core.authority.AuthorityUtils import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.oauth2.core.user.DefaultOAuth2User import org.springframework.security.oauth2.core.user.OAuth2User import org.springframework.security.web.SecurityFilterChain import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter import org.springframework.security.web.authentication.WebAuthenticationDetailsSource import org.springframework.security.web.util.matcher.AntPathRequestMatcher import org.springframework.web.filter.OncePerRequestFilter @TestConfiguration @EnableWebSecurity class SpringSecurityTestConfig { @Primary @Bean fun securityFilterChain(http: HttpSecurity): SecurityFilterChain? { http.authorizeHttpRequests { auth -> auth .requestMatchers(AntPathRequestMatcher.antMatcher("/h2-console/**")).permitAll() .anyRequest().permitAll() }.csrf().disable().securityContext() http.addFilterBefore(object : OncePerRequestFilter() { override fun doFilterInternal( request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain ) { logger.debug(request.requestURI) val oauth2User: OAuth2User = DefaultOAuth2User( AuthorityUtils.createAuthorityList("SCOPE_message:read"), mapOf(Pair("email", "dummy@dymmy")), "email" ) val authentication = UsernamePasswordAuthenticationToken( oauth2User, null ) authentication.details = WebAuthenticationDetailsSource().buildDetails(request) SecurityContextHolder.getContext().authentication = authentication filterChain.doFilter(request, response) } }, UsernamePasswordAuthenticationFilter::class.java) return http.build() } }