Ответы пользователя по тегу Spring
  • Почему не удается авторизоваться spring rest jwt?

    @dreven Автор вопроса
    Решил проблему, оказывается когда я в UserDetailsServiceпередавал объект в методе loadUserByUsername, который был создан на основе UserDetails, забыл в геттерах username и password вернуть объекты, и не надо отправлять хешированный пароль. Все работает.
    Метод:
    @Override
        @Transactional
        public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
    
            User user = userRepository.findByUserName(userName)
                    .orElseThrow(() ->
                            new UsernameNotFoundException("User not found with username: " + userName)
                    );
           UserPrincipal userPrincipal = UserPrincipal.create(user);
           logger.info("user with name: {} succesfully loaded", userPrincipal.getUsername());
           return userPrincipal;
        }


    Объект:
    @Data
    @Builder(toBuilder = true)
    @NoArgsConstructor
    public class UserPrincipal implements UserDetails {
    
        static Logger logger = LoggerFactory.getLogger(UserPrincipal.class);
    
        private Long id;
    
        private String name;
    
        private String username;
    
        private String lastname;
    
        private String middlename;
    
        private String password;
    
        private Collection<? extends GrantedAuthority> authorities;
    
        public UserPrincipal(Long id, String username, String name, String password, String lastname, String middlename, Collection<? extends GrantedAuthority> authorities) {
            this.id = id;
            this.name = name;
            this.username = username;
            this.lastname = lastname;
            this.middlename = middlename;
            this.password = password;
            this.authorities = authorities;
    
        }
    
        public static UserPrincipal create(User user) {
            logger.info(user.toString());
            List<GrantedAuthority> authorities = user.getRoles().stream().map(role ->
                    new SimpleGrantedAuthority(role.getRole())
            ).collect(Collectors.toList());
    
            return new UserPrincipal(
                    user.getId(),
                    user.getUserName(),
                    user.getName(),
                    user.getPassword(),
                    user.getLastName(),
                    user.getMiddleName(),
                    authorities
            );
        }
    
        @Override
        public Collection<? extends GrantedAuthority> getAuthorities() {
            return authorities;
        }
    
        @Override
        public String getPassword() {
            return password;
        }
    
        @Override
        public String getUsername() {
            return username;
        }
    
        @Override
        public boolean isAccountNonExpired() {
            return true;
        }
    
        @Override
        public boolean isAccountNonLocked() {
            return true;
        }
    
        @Override
        public boolean isCredentialsNonExpired() {
            return true;
        }
    
        @Override
        public boolean isEnabled() {
            return true;
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            UserPrincipal that = (UserPrincipal) o;
            return Objects.equals(id, that.id);
        }
    
        @Override
        public int hashCode() {
    
            return Objects.hash(id);
        }

    @PostMapping("/signin")
        public ResponseEntity<?> authenticateUser(@Valid @RequestBody LoginRequest loginRequest) {
            String username = loginRequest.getUserName();
            String password = loginRequest.getPassword();
            Authentication authentication;
            try {
                authentication = authenticationManager.authenticate(
                        new UsernamePasswordAuthenticationToken(
                                username,
                                password
                        )
                );
            } catch (AuthenticationException e) {
                logger.error("Invalid username/password supplied");
                throw new BadCredentialsException("Invalid username/password supplied");
            }
            SecurityContextHolder.getContext().setAuthentication(authentication);
    
            String jwt = tokenProvider.generateToken(authentication);
            return ResponseEntity.ok(new JwtAuthenticationResponse(jwt));
    
        }
    Ответ написан
    Комментировать