paatriksirbu / CasoPractico

0 stars 0 forks source link

Configurar Spring Security #1

Open paatriksirbu opened 2 months ago

paatriksirbu commented 2 months ago

Implementar la configuracion basica de Spring. Configuracion basada en roles y permisos para los diferentes usuarios del sistema.

jvacdragon commented 2 months ago

Hey, if your problem is with basic auth configuration in spring security for an stateless API, maybe this code can help you:

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.Customizer; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain;

@Configuration public class BasicAuthSecurityConfiguration {

//config de requests
@Bean
SecurityFilterChain securtyFilterChain(HttpSecurity http) throws Exception{
    http.authorizeHttpRequests(auth -> {
        auth.anyRequest().authenticated();
    });

    http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

    http.httpBasic(Customizer.withDefaults());

    http.csrf(csrf-> csrf.disable());

    return http.build();
}

//config users
@Bean
public UserDetailsService userDetailsService(){

    var user = User.withUsername("USERNAME")
            .password("PASSWORD") //if your password is not encoded, then include {noop} before the password
            .roles("ROLE") //role name, example: USER
            .build();

    return new InMemoryUserDetailsManager(user, admin);
}

}