No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Implementar la interface UserDetailsService

13/23
Recursos

Aportes 7

Preguntas 4

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

ctrl + o -> para borrar las importaciones no usadas
Para los que tengan un entero de ID en vez de un string en su model Usuario, en el repositorio pueden crear el metodo findByUsername, para usarlo en lugar de findById. **RepositoryUsuario** import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; public interface IUsuarioRepository extends JpaRepository\<Usuario, Integer> { Optional\<Usuario> findByUsername(String username); }

UserSecurityService

package com.platzi.pizza.service;

import com.platzi.pizza.persistence.entity.UserEntity;
import com.platzi.pizza.persistence.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserSecurityService implements UserDetailsService {

    private final UserRepository userRepository;

    @Autowired
    public UserSecurityService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserEntity userEntity = this.userRepository.findById(username)
                .orElseThrow(() -> new UsernameNotFoundException("User " + username + " not found."));

        return User.builder()
                .username(userEntity.getUsername())
                .password(userEntity.getPassword())
                .roles("ADMIN")
                .accountLocked(userEntity.isLocked())
                .disabled(userEntity.isDisabled())
                .build();
    }
}

UserRepository ```js package com.platzi.pizzeria.persistence.repository; import com.platzi.pizzeria.persistence.entity.UserEntity; import org.springframework.data.repository.CrudRepository; public interface UserRepository extends CrudRepository<UserEntity, String> {} ```UserSecurityService ```js package com.platzi.pizzeria.service; import com.platzi.pizzeria.persistence.entity.UserEntity; import com.platzi.pizzeria.persistence.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class UserSecurityService implements UserDetailsService { private final UserRepository userRepository; @Autowired public UserSecurityService(UserRepository userRepository) { this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserEntity userEntity = this.userRepository.findById(username) .orElseThrow(() -> new UsernameNotFoundException("User + " + username + " NOT FOUND")); return User.builder() .username(userEntity.getUsername()) .password(userEntity.getPassword()) .roles("ADMIN") .accountLocked(userEntity.getLocked()) .disabled(userEntity.getDisabled()) .build(); } } ``` SecurityConfig ```js package com.platzi.pizzeria.web.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpMethod; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .csrf(AbstractHttpConfigurer::disable) .cors(Customizer.withDefaults()) .authorizeHttpRequests((authorize) -> authorize .requestMatchers(HttpMethod.GET, "/api/pizzas/**").hasAnyRole("ADMIN", "CUSTOMER") .requestMatchers(HttpMethod.POST, "/api/pizzas/**").hasRole("ADMIN") .requestMatchers(HttpMethod.PUT).hasRole("ADMIN") .requestMatchers("/api/orders/**").hasRole("ADMIN") .anyRequest() .authenticated() ) .httpBasic(Customizer.withDefaults()) ; return http.build(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ```
Que puedo hacer si mi Id es de tipo int?
Me agrado le entendí muy bien si se desea agregar más operaciones, como borrar, actualizar o crear usuarios se podrida configurar un UserDetailsManager

✅