Fakultas Ilmu Komputer UI

Skip to content
Snippets Groups Projects

WebSecurityConfig.java

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by Fathan Hadyan
    Edited
    WebSecurityConfig.java 2.05 KiB
    package apap.tutorial.manpromanpro.security;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.Customizer;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.security.web.SecurityFilterChain;
    import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
    
    
    @Configuration
    @EnableWebSecurity
    public class WebSecurityConfig {
    
    	@Autowired
        private UserDetailsService userDetailsService;
    
        @Bean
        public SecurityFilterChain webFilterChain(HttpSecurity http) throws Exception{
            http.csrf(Customizer.withDefaults())
                .authorizeHttpRequests (requests -> requests
                    .requestMatchers (new AntPathRequestMatcher("/css/**")).permitAll() 
                    .requestMatchers (new AntPathRequestMatcher("/js/**")).permitAll()
                    .anyRequest().authenticated()
                )   
                .formLogin((form) -> form
                    .loginPage("/login")
                    .permitAll()
                    .defaultSuccessUrl("/")
                )
                .logout((logout) -> logout.logoutRequestMatcher(new AntPathRequestMatcher( "/logout")) 
                        .logoutSuccessUrl("/login"));
    
            return http.build();
        }
    
        @Bean
        public BCryptPasswordEncoder encoder(){
            return new BCryptPasswordEncoder();
        }   
    
        @Autowired
        public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception{
            auth.userDetailsService(userDetailsService).passwordEncoder(encoder());
        }
    }
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Please register or to comment