How do I configure @PreAuthorize to recognize the ID of my logged in user?

前端 未结 2 2002
一整个雨季
一整个雨季 2021-01-27 03:32

I\'m trying to create a Spring Boot 2.1 application. I have created the following rest controller ...

@RestController
@RequestMapping("/api/users")
pub         


        
2条回答
  •  借酒劲吻你
    2021-01-27 03:43

    1. Create a CustomUser class which is subclass of org.springframework.security.core.userdetails.User
      import org.springframework.security.core.GrantedAuthority;
      import org.springframework.security.core.userdetails.User;
    
      import java.util.Collection;
      import java.util.UUID;
    
      public class CustomUser extends User {
      
        private final UUID id;
      
        public UUID getId() {
         return id;
        }
    
        public CustomUser(UUID id, String username, String password,
                    Collection authorities) {
         super(username, password, authorities);
         this.id = id;
        }
    
        public CustomUser(UUID id, String username, String password, 
                        boolean enabled, boolean accountNonExpired, 
                        boolean credentialsNonExpired, 
                        boolean accountNonLocked, 
                      Collection authorities) {
        super(username, password, enabled, 
              accountNonExpired, credentialsNonExpired, 
              accountNonLocked, authorities);
            this.id = id;
        }
     }
    
    1. Update DatabaseUserDetailsService to return this CustomUser
      @Service
      public class DatabaseUserDetailsService implements UserDetailsService {
    
        @Autowired
        private IUserRepository userRepository;
    
        @Override
        public UserDetails loadUserByUsername(String username)
                throws UsernameNotFoundException {
            User user = userRepository.findByEmail(username);
            return new CustomUser(user.getId(), user.getUsername(),
                    user.getPassword(), user.getAuthorities());
        }
    
      }
    

    Note

    • Ensure you have @EnableGlobalMethodSecurity enabled, otherwise @PreAuthorize is not evaluated

提交回复
热议问题