Untitled

mail@pastecode.io avatarunknown
plain_text
2 months ago
1.2 kB
3
Indexable
Never
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN") // Hanya pengguna dengan role "ADMIN" yang bisa akses /admin
                .antMatchers("/user").hasAnyRole("USER", "ADMIN") // Pengguna dengan role "USER" atau "ADMIN" bisa akses /user
                .anyRequest().authenticated() // Semua permintaan harus diautentikasi
            .and()
            .formLogin()
                .permitAll() // Izinkan akses ke halaman login untuk semua orang
            .and()
            .exceptionHandling()
                .accessDeniedPage("/access-denied"); // Halaman akses ditolak
    }

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