Home > OS >  Getting org.springframework.security.access.AccessDeniedException: Access Denied Even After data sav
Getting org.springframework.security.access.AccessDeniedException: Access Denied Even After data sav

Time:01-12

This is my controller class code which I am using for getting user and save that particular user in database but after hitting data/or sending the data it was committed to my database but after that I am getting this error message.

package com.app.Exam.USerController;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.app.Exam.Models.Roles;
import com.app.Exam.Models.User;
import com.app.Exam.Models.UserRoll;
import com.app.Exam.Service.UserService;

@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    
    @Autowired
 private PasswordEncoder bCryptPasswordEncoder;
    
    @PostMapping("/")
    public User createUser(@RequestBody User user) throws Exception {
        
        User user2=new User();
        user2.setPassword(this.bCryptPasswordEncoder.encode(user.getPassword()));
        user2.setEmail(user.getEmail());
        user2.setFirstName(user.getFirstName());
        user2.setLastName(user.getLastName());
        user2.setPhone(user.getPhone());
        user2.setUserName(user.getUserName());
        
        Roles roll=new Roles();
        //roll.setRollId(46L);
        roll.setRollName("NORMAL");
        
        
        //user.setUserRolls(list);
        
        List<UserRoll> list=new ArrayList<>();
        UserRoll userRoll=new UserRoll();
        userRoll.setRoles(roll);
        userRoll.setUser(user2); 
        list.add(userRoll);
        roll.setUserRolls(list);
        
        
        
 User local=this.userService.CreateUser(user2,list);
     
     return local;
    }
    
    @GetMapping("/{username}")
    private User getUserByName(@PathVariable("username") String username) {
    User user=this.userService.getUserByName(username);
    return user;
    }
    
//  @GetMapping("/{id}")
//  private User deleteUser(@PathVariable("id") Long id) throws Exception {
//  User user=this.userService.deleteUserbyid(id);
//  return user;
//  }

}

My spring security config class was as below:

package com.app.Exam.Security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.app.Exam.JwtConfig.JwtAuthenticationEntryPoint;
import com.app.Exam.JwtConfig.JwtRequestFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {
    @Autowired
    private UserDetailsService userDetailsService;
    
    @Autowired
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    JwtRequestFilter jwtAuthenticationFilter;
    
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{
         
    
        http
        .csrf().disable().cors().disable()
        .authorizeHttpRequests() 
        .requestMatchers("/Authenticate","/user/").permitAll()
        .requestMatchers(HttpMethod.OPTIONS).permitAll()
        .anyRequest().authenticated()  
        .and()
        .exceptionHandling()
        .authenticationEntryPoint(jwtAuthenticationEntryPoint)
        .and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authenticationProvider(this.daoAuthenticationProvider());
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        
    return  http.build();
        
    }
//  @Override
//  protected void configure(HttpSecurity http) throws Exception {
//      http
//      .csrf().disable().cors()
//      .disable().authorizeHttpRequests().antMatchers("/Authenticate","/user/").permitAll()
//      .antMatchers(HttpMethod.OPTIONS).permitAll()
//      .anyRequest().authenticated() 
//      .and()
//      .exceptionHandling()
//      .authenticationEntryPoint(jwtAuthenticationEntryPoint)
//      .and()
//      .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
//      
//      http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
//      }
//  
    @Bean  
    PasswordEncoder pass() {
        return new BCryptPasswordEncoder(); 
    } 
    
//  @Bean
//  AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
//      return authenticationConfiguration.getAuthenticationManager();
//  }
     
    @Bean
    AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { 
        return authenticationConfiguration.getAuthenticationManager();
    }
    
    @Bean
    DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider=new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(this.userDetailsService);
        daoAuthenticationProvider.setPasswordEncoder(this.pass());
        return daoAuthenticationProvider;
    }

}

My errors Stackstrace is as belows.. enter image description here enter image description hereenter code here enter image description here

CodePudding user response:

After to many reaserch i found my answer this error happens because i am not providing the user roll from front end and defining it harrcoded in my backend if we wanted to do that we have to specify that property in model with @JsonIgnore like bellow one

@OneToMany(cascade = CascadeType.ALL ,fetch = FetchType.EAGER,mappedBy ="user")

@JsonIgnore

private List userRolls=new ArrayList<>();

it informs the serverlet request to egnore the null json of that specific property......

For this kind of databind errors use @JsonIgnore it works for me. this is jaxb databind error thats why spring security throwing Access denied error After Commiting data to Db...

  • Related