'Getting the principal in an AOP interceptor using webflux
I implemented a webflux web API with working oauth authentication (I'm getting the @AuthenticatedPrincipal in controllers). My problem is that I want to implement an AOP interceptor for mybatis Executor, because I need to perform operations based on the Principal identity when an update is performed on DB. I tried to access the Principal through the ReactiveSecurityContextHolder, but the returned SecurityContext is always null...
@Intercepts(@Signature(type = Executor.class, method = "update", args={MappedStatement.class, Object.class}))
public class BaseEntityInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
// get sql
SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
// get parameter , this is the target object that you want to handle
Object parameter = invocation.getArgs()[1];
// make sure super class is BaseEntity
if (parameter instanceof BaseEntityModel) {
//init
BaseEntityModel baseEntity = (BaseEntityModel) parameter;
SecurityContext context= ReactiveSecurityContextHolder.getContext().block();
Authentication authentication= context.getAuthentication();
Principal principal = (Principal)authentication.getPrincipal();
if (SqlCommandType.UPDATE.equals(sqlCommandType)) {
baseEntity.initUpdate(principal.getUsername());
}
}
return invocation.proceed();
}
...
}
What is the correct way to access the Principal? I understand that normally the SecurityContext is saved in ThreadLocal, and probably I must "share" it with my interceptor... how?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
