Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to disable csrf spring security 4

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 4.63k
    Comment on it

    In spring security bydefault the csrf protect in on. As a result it asks for token during login and other requests. Although its not a good practise to disable the protection but we can do it. As we can see in the code below, http.csrf().disable() , it will disable it. If this line will be omitted it will be enabled.

    @Configuration
    @EnableWebSecurity
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    
        @Autowired
        @Qualifier("userDetailsService") // user defined service with service name "userDetailsService"
        private UserDetailsService userDetailsService;
    
        @Autowired
        public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
    
         //password in encrypted in md5format
            auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); 
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
    
          http
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/", "/homepage/**").permitAll()
            .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
            .antMatchers("/db/**").access("hasRole('ROLE_ADMIN') and hasRole('DBA')")
            .and().formLogin().loginPage("/login").successHandler(loginSuccessHandler)
            .usernameParameter("username").passwordParameter("password");
        }
    
    
        @Bean
        public Md5PasswordEncoder passwordEncoder() throws Exception {
          return new Md5PasswordEncoder();
        }
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: