How to configure the Auditor using Spring Boot 2.0.2

1

Here is a class I used with the spring framework version 4.3.4.RELEASE (I still did not use the spring boot) and it worked:

import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SpringSecurityAuditor implements AuditorAware<String> {

    @Override
    public String getCurrentAuditor() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null || authentication.getPrincipal().equals("anonymousUser")) {

            return authentication.getPrincipal().toString();
        }

        return ((UsuarioLogado) authentication.getPrincipal()).getUsername();
    }

}

And here's what I'm trying to implement with spring boot 2.0.2:

import java.util.Optional;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SpringSecurityAuditor implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null || authentication.getPrincipal().equals("anonymousUser")) {

            return (Optional<String>) authentication.getPrincipal();
        }
        return ... código a  ser implementado...
    }
}

But I can not do this. How can I implement this method?

    
asked by anonymous 23.05.2018 / 19:02

1 answer

0

I'll consider your old implementation, which returns String , not a user entity, for example. In addition, I will not consider anything that would lead you to believe that you are using custom things for user details, security holder / manager, etc.

In this case, the only change is that a Optional - AuditorAware 1.x , AuditorAware current . The implementation will be basically the same, just the altered return, something like the below:

public class SpringSecurityAuditor implements AuditorAware<String> {

    @Override
    public Optional<String> getCurrentAuditor() {
        String currentAuditor;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || authentication.getPrincipal().equals("anonymousUser")) {
            currentAuditor = authentication.getPrincipal().toString();
        } else {
            currentAuditor = ((UsuarioLogado) authentication.getPrincipal()).getUsername()
        }
        return Optional.of(currentAuditor);
    }

}

It should be noted that this does not necessarily relate to Spring Boot , the interface comes from Spring Data , in the case of Commons . Related to Boot , the configuration is simplified, but that's another issue.

    
24.05.2018 / 16:18