Hello! How can I get an authorized user, that is, after authorization to extract the object of this user from the database, for example, in order to fill in the fields on his profile page, I have implemented DAO using hibernate and the authorization itself is done from the database. Thank you in advance!

    2 answers 2

    To do this, you first need to get the user name from spring-security

    public String getCurrentUsername() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); return auth.getName(); } 

    and pass it to hibernate

     public User getUserByUsername(String username) { CriteriaQuery<User> criteriaQuery = em.getCriteriaBuilder().createQuery(User.class); Root<User> userRequest = criteriaQuery.from(User.class); Expression<String> exp = userRequest.get("username"); Predicate predicate = exp.in(username); criteriaQuery.where(predicate); try { return em.createQuery(criteriaQuery).getSingleResult(); } catch (NoResultException e) { return new User(); } } 
    • Yes, an important feature, as noted by @Nofate, the spring user and the object from the database are different entities - cadmy

    Starting with Spring-Security 3.2, it is more convenient to use the @AuthenticationPrincipal annotation on the argument of your controller's method.

     ModelAndView someRequestHandler(@AuthenticationPrincipal User user) { // ... } 

    User is exactly the sprung user, not the object that you put into the database.

    For this to work, you need to register the AuthenticationPrincipalArgumentResolver bin:

    • when using the Java configuration, @EnableWebMvcSecurity annotation to your @Configuration -bin;

    • when using the xml configuration, register it with <mvc:argument-resolvers> :

       <mvc:annotation-driven> <mvc:argument-resolvers> <bean class="AuthenticationPrincipalArgumentResolver"/> </mvc:argument-resolvers> </mvc:annotation-driven>