keycloak 事件监听的spi开发测试
1. 新建简单maven工程
注意keycloak包的scope为provided
如
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-services</artifactId>
<version>4.8.3.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-core</artifactId>
<version>4.8.3.Final</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-server-spi</artifactId>
<version>4.8.3.Final</version>
<scope>provided</scope>
</dependency>
...
- 如要相关依赖打肥包
可以使用插件maven-assembly-plugin
2. spi开发
- 实现EventListenerProvider
public class MyEventListenerProvider implements EventListenerProvider{
org.slf4j.Logger log = LoggerFactory.getLogger(MyEventListenerProvider.class);
private List<Event> events;
public MyEventListenerProvider(List<Event> events) {
System.out.println("events构造方法");
this.events = events;
}
@Override
public void onEvent(Event event) {
System.out.println("deng"+event.getTime()+" realmId:"+event.getRealmId()+" type:"+event.getType().name());
log.info(event.getClientId());
events.add(event);
}
@Override
public void close() {
}
@Override
public void onEvent(AdminEvent event, boolean includeRepresentation) {
// Assume this implementation just ignores admin events
System.out.println("deng"+event.getTime());
}
}
2.实现EventListenerProviderFactory
public class MyEventListenerProviderFactory implements EventListenerProviderFactory {
private List<Event> events;
public String getId() {
return "my-deng";
}
public void init(Config.Scope config) {
System.out.println("init " );
events = new LinkedList();
}
public void postInit(KeycloakSessionFactory factory) {
}
public EventListenerProvider create(KeycloakSession session) {
System.out.println("create "+session.getContext().getContextPath());
return new MyEventListenerProvider(events);
}
public void close() {
}
}
- 建立META-INF\services文件夹
以实现的接口全限定类名为文件名,文件内容为具体实现类的全限定类名
文件名称:org.keycloak.events.EventListenerProviderFactory
内容: com.dengji85.keycloak.spi.MyEventListenerProviderFactory
3. 部署
将打好的jar包copy到keycloak主目录\standalone\deployments
这个目录会自动部署也支持热部署
在管理控制台配置事件监听器
访问服务端查看日志信息:
参考:
*Keycloak SPI adding a custom event listener module
*keycloak SPI 开发讲解
*keycloak老版本文档