2017-10-29 49 views
0

我有一个Spring数据存储库。 当调用http://localhost:8080/persons webservice时,我想记录一些东西。我不想让MyCustomRepository <>。清洁选项?如何在弹簧数据存储库方法之前打印某些日志,但没有自定义回购

回购类:

@RepositoryRestResource(collectionResourceRel = "persons", path = "persons") 
public interface PersonRepository extends PagingAndSortingRepository<Person, Long> { 

    List<Person> findByLastName(@Param("name") String name); 

示例日志:

log.error("AccessToken: " + securityContext.getTokenString()); 
log.error("User: {}/{}", accessToken.getPreferredUsername(), accessToken.getName()); 
log.error("Principal: {}", principal.getName()); 

回答

1

您可以创建一个方面拦截到您的通话PersonRepository。从那里您可以访问OAuth2访问令牌和安全上下文来检索主体。下面是一个例子,

@Component 
@Aspect 
@Log 
public class SecurityAspect { 

    @Autowired 
    private OAuth2ClientContext oauth2ClientContext; 

    @Pointcut("execution(public * my.example.repository.PersonRepository.*(..))") 
    public void pointcut() { 
    } 

    @Around("pointcut()") 
    public Object advice(ProceedingJoinPoint pjp) throws Throwable { 
     log.info(
       "Entering SecurityAspect.advice() in class " 
         + pjp.getSignature().getDeclaringTypeName() 
         + " - method: " + pjp.getSignature().getName()); 

     OAuth2AccessToken accessToken = oauth2ClientContext.getAccessToken(); 
     log.info("AccessToken: " + accessToken); 

     if (SecurityContextHolder.getContext().getAuthentication() 
       instanceof OAuth2Authentication) { 
      OAuth2Authentication authentication = 
        (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication(); 
      if (authentication.getUserAuthentication() instanceof UsernamePasswordAuthenticationToken) { 
       UsernamePasswordAuthenticationToken userToken = 
         (UsernamePasswordAuthenticationToken) authentication.getUserAuthentication(); 
       log.info("Principal id: " + userToken.getPrincipal()); 
       if (userToken.getDetails() instanceof Map) { 
        Map details = (Map) userToken.getDetails(); 
        log.info("Principal Name: " + details.get("name")); 
       } 
      } 
     } 

     return pjp.proceed(); 
    } 
} 
+0

感谢您的快速示例。这是横切方面最干净的方式。我试图将两个不同的切入点()分成一个Advice()[一个来自.ws包,另一个来自.rest包]。将检查如何做到这一点。 – Espresso

相关问题