No tienes acceso a esta clase

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

Aplicar requestMatchers con roles

11/23
Recursos

Aportes 4

Preguntas 0

Ordenar por:

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

package com.platzi.pizza.web.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http
                .csrf().disable()
                .cors()
                .and()
                .authorizeHttpRequests()
                .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()
                .and()
                .httpBasic();

        return http.build();

    }

    @Bean
    public UserDetailsService memoryUsers() {

        UserDetails admin = User.builder()
                .username("admin")
                .password(passwordEncoder().encode("admin"))
                .roles("ADMIN")
                .build();

        UserDetails customer = User.builder()
                .username("customer")
                .password(passwordEncoder().encode("customer123"))
                .roles("CUSTOMER")
                .build();

        return new InMemoryUserDetailsManager(admin, customer);

    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

Para quienes estan trabajando con versiones de Spring Security superior a la del curso y les aparecen varios metodos deprecados:@Configuration @EnableWebSecurity public class WebSecurityConfig { public static final String *ADMIN* = "ADMIN"; public static final String *CUSTOMER* = "CUSTOMER"; @Bean public SecurityFilterChain configure(HttpSecurity http, CorsConfig corsConfig) throws Exception { http .csrf(AbstractHttpConfigurer::disable) .cors(cors -> cors.configurationSource(corsConfig.corsConfigurationSource())) .authorizeHttpRequests(requests -> requests .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 UserDetailsService memoryUsers() { UserDetails admin = User.*builder*() .username("admin") .password(passwordEncoder().encode("admin")) .roles(*ADMIN*) .build(); UserDetails customer = User.*builder*() .username("customer") .password(passwordEncoder().encode("customer123")) .roles(*CUSTOMER*) .build(); return new InMemoryUserDetailsManager(admin, customer); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ```java @Configuration @EnableWebSecurity public class WebSecurityConfig { public static final String ADMIN = "ADMIN"; public static final String CUSTOMER = "CUSTOMER"; @Bean public SecurityFilterChain configure(HttpSecurity http, CorsConfig corsConfig) throws Exception { http .csrf(AbstractHttpConfigurer::disable) .cors(cors -> cors.configurationSource(corsConfig.corsConfigurationSource())) .authorizeHttpRequests(requests -> requests .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 UserDetailsService memoryUsers() { UserDetails admin = User.builder() .username("admin") .password(passwordEncoder().encode("admin")) .roles(ADMIN) .build(); UserDetails customer = User.builder() .username("customer") .password(passwordEncoder().encode("customer123")) .roles(CUSTOMER) .build(); return new InMemoryUserDetailsManager(admin, customer); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ```

✅

```java 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.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.provisioning.InMemoryUserDetailsManager; 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 InMemoryUserDetailsManager memoryUsers() { UserDetails admin = User.builder() .username("admin") .password(passwordEncoder().encode("admin")) .roles("ADMIN") .build(); UserDetails customer = User.builder() .username("customer") .password(passwordEncoder().encode("customer123")) .roles("CUSTOMER") .build(); return new InMemoryUserDetailsManager(admin, customer); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ```