Get the current user at the service level

I want the current user to be in the service tier

I have tried the following code, but I get a null pointer exception

@Service
public class MyService{

@Autowired
TodoRepository todoRepository;

public void execute(){
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    Todo todo = new Todo();
    todo.setDomain(auth.getName());
    todoRepository.save(todo);  
} 

      

Can someone show me how I can login using spring service layer security?

+3


source to share


1 answer


This will help you find the authenticated user:

 @Override
    public Person getCurrentlyAuthenticatedUser() {

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

        if (authentication == null) {
            return null;
        } else {
            // The line below calls the method from my Person database, 
            // where I search users by their Email(username)
            return personDAO.findPersonByUsername(authentication.getName());
        }
    }

      



Hope this helps. If not, please give me kno, w i will delete my answer.

0


source







All Articles