Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Access Denied in spring security 4 even after successful authentication

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.73k
    Comment on it

    In spring security after successfull authentication I was getting the Access denied error to go to pages which had the authentication.

    What I did was.

    @Override
        protected void configure(HttpSecurity http) throws Exception {
    
          http
            .authorizeRequests()
            .antMatchers("/", "/homepage/**").permitAll()
            .antMatchers("/admin/**").access("hasRole('ADMIN')")
            .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
            .and().formLogin().loginPage("/login")
            .usernameParameter("username").passwordParameter("password")
            .and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }
    

    Here the mistake was the role is authneticated if its written completely with ROLE_ prefix. In DB also it should be stored with ROLE_ prefix. Here is the updated code which worked well.

    @Override
        protected void configure(HttpSecurity http) throws Exception {
    
          http
            .authorizeRequests()
            .antMatchers("/", "/homepage/**").permitAll()
            .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
            .antMatchers("/db/**").access("hasRole('ROLE_ADMIN') and hasRole('ROLE_DBA')")
            .and().formLogin().loginPage("/login")
            .usernameParameter("username").passwordParameter("password")
            .and().exceptionHandling().accessDeniedPage("/Access_Denied");
    }
    

 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: