2017-10-29 8 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

ありがとうございます。それがこのクロスカットの側面にとって最もクリーンな方法です。私は2つの異なるポイントカット()をoneAdvice()[1つは.wsパッケージから、もう1つは.restパッケージから]に送りこうとしていました。それを行う方法をチェックします。 – Espresso

関連する問題