스프링 부트 - 키클로크를 비활성화하는 방법은 무엇입니까?
키클로크가 통합된 스프링 부트 프로젝트가 있습니다.이제 테스트 목적으로 키클로크를 비활성화하려고 합니다.
를 추가하여 시도했습니다.keycloak.enabled=false로.application.propertiesKeycloak 설명서에 언급된 대로 작동하지 않았습니다.
그러면 어떻게 비활성화해야 할까요?
2022년 업데이트
발등에 대한 이 훌륭한 가이드를 따라주시기 바랍니다.
같은 문제를 겪고 있는 사람들을 위해, 제가 한 일은 이렇습니다.
나는 Keyclock을 비활성화하지 않았지만 테스트 목적으로 별도의 Keyclock 구성 파일을 만들었습니다.
구성 파일입니다.
@Profile("test")
@Configuration
@EnableWebSecurity
public class SecurityTestConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").permitAll();
http.headers().frameOptions().disable();
http.csrf().disable();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/**");
}
@Bean
@Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public AccessToken accessToken() {
AccessToken accessToken = new AccessToken();
accessToken.setSubject("abc");
accessToken.setName("Tester");
return accessToken;
}
}
테스트 환경에서만 사용하는 것이 중요하므로 다음과 같이 구성에 주석을 달았습니다.@Profile("test")나는 또한 추가했습니다.AccessToken응용 프로그램의 감사 기능 중 일부가 이에 의존하기 때문입니다.
효과가 있어야 하는데, 이에 대한 지라 티켓에 대한 마지막 댓글을 보니 그렇지 않은 것 같습니다.
설명 상태로 키클록에 대한 스프링 부트 자동 구성을 제외할 수 있습니다.application.properties:spring.autoconfigure.exclude=org.keycloak.adapters.springboot.KeycloakSpringBootConfiguration
키 클럭 자동 구성을 제외해야 합니다.이 작업을 수행하려면 관련 스프링 구성 파일(application.properties)에 이 항목을 추가하면 됩니다.
spring.autoconfigure.exclude = org.keycloak.adapters.springboot.KeycloakAutoConfiguration
내 해결 방법:
사용자 정의 필터를 생성하여 초기 위치의 (Spring) Security-Chain에 추가합니다.
application.yml에 플래그를 만듭니다(securityEnabled).
사용자 지정 필터에서 플래그를 쿼리합니다.'true'인 경우 chain.doFilter()를 호출하여 다음 필터를 계속합니다.'false'인 경우 더미 Keyclock-Account를 생성하여 필요한 역할을 설정하고 컨텍스트로 설정합니다.
그런데 역할도 애플리케이션에 아웃소싱됩니다.yml
보안 체인의 나머지 필터를 건너뜁니다(그러므로 키클록-stuff가 실행되지 않고 해당 인증이 발생합니다).
세부 정보:
사용자 정의 필터 클래스
public class CustomFilter extends OncePerRequestFilter {
@Value("${securityEnabled}")
private boolean securityEnabled;
@Value("${grantedRoles}")
private String[] grantedRoles;
@Override
public void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
FilterChain chain) throws IOException, ServletException {
if (!securityEnabled){
// Read roles from application.yml
Set<String> roles = Arrays.stream(grantedRoles)
.collect(Collectors.toCollection(HashSet::new));
// Dummy Keycloak-Account
RefreshableKeycloakSecurityContext session = new RefreshableKeycloakSecurityContext(null, null, null, null, null, null, null);
final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<>("Dummy_Principal", session);
final KeycloakAccount account = new SimpleKeycloakAccount(principal, roles, principal.getKeycloakSecurityContext());
// Dummy Security Context
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(new KeycloakAuthenticationToken(account, false));
SecurityContextHolder.setContext(context);
// Skip the rest of the filters
req.getRequestDispatcher(req.getServletPath()).forward(req, res);
}
chain.doFilter(req, res);
}
}
Spring-Security의 http-Configuration에 Custom-Filter 삽입
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http
.cors()
.and()
.csrf()
.disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.sessionAuthenticationStrategy(sessionAuthenticationStrategy())
.and()
.addFilterAfter(CustomFilter(), CsrfFilter.class)
.authorizeRequests()
.anyRequest().permitAll();
}
Keyclock을 구성한 후 기본 필터 체인을 확인합니다.
필터 체인
따라서 전체 Keyclock-Magic을 피하기 위해 5번 위치에 사용자 정의 필터를 삽입하는 것이 분명합니다.
이 해결 방법을 사용하여 메서드 보안을 해제했습니다. 이 해결 방법은 @Secured-Annotation입니다.
스프링 부트 2.5.6 및 키클로크 16.1.0에 대한 답변 업데이트
application.properties에서 다음을 설정합니다.
spring.autoconfigure.exclude=org.keycloak.adapters.springboot.KeycloakAutoConfiguration
(자동 구성 클래스 이름은 이전 답변 이후 변경됨)
키클록 어댑터 종속성은 표준 스프링 보안 자동 구성도 제공하므로 둘 다 사용하지 않으려면 다음을 사용합니다.
spring.autoconfigure.exclude=org.keycloak.adapters.springboot.KeycloakAutoConfiguration,org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
언급URL : https://stackoverflow.com/questions/47861513/spring-boot-how-to-disable-keycloak
'programing' 카테고리의 다른 글
| Gradle | 스프링 부트 종속성은 제외되지 않습니다. (0) | 2023.08.02 |
|---|---|
| 스크립트에서 stdout을 캡처하시겠습니까? (0) | 2023.08.02 |
| 처음과 마지막 큰따옴표를 어떻게 벗길 수 있습니까? (0) | 2023.08.02 |
| UI 도구 모음에 UI 레이블 추가 (0) | 2023.08.02 |
| SSIS vs.오라클 데이터 통합업체 (0) | 2023.08.02 |