简体   繁体   中英

@PreAuthorize("hasRole('ROLE_ADMIN')") is throwing Forbidden

I am using @PreAuthorize("hasRole('ROLE_ADMIN')") to restrict the method access to only for the admin for that I have write the follwoing method

@CrossOrigin(origins="http://localhost:4200")
@RestController
@RequestMapping("/api/v1")
public class BasicAuthController {
        @PreAuthorize("hasRole('ROLE_ADMIN')")
        @DeleteMapping(path = "/deleteUser/{userId}")
        public ResponseEntity<?> deleteUser(@PathVariable int userId) {
            authenticationService.deleteUser(userId);
            return ResponseEntity.ok((""));
        }

}

My configuaration call is like below

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true, proxyTargetClass = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

@Autowired
private UserDetailsService jwtUserDetailsService;

@Autowired
private JwtRequestFilter jwtRequestFilter;

 @Autowired
 private DataSource dataSource;

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

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    // configure AuthenticationManager so that it knows from where to load
    // user for matching credentials
    // Use BCryptPasswordEncoder
    auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()      
     .headers()
      .frameOptions().sameOrigin()
      .and()
        .authorizeRequests()
         .antMatchers("/api/v1/authenticate", "/api/v1/register","/api/v1/basicauth").permitAll()
            .antMatchers("/").permitAll()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/home")
            .failureUrl("/login?error")
            .permitAll()
            .and()
        .logout()
         .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
         .logoutSuccessUrl("/login?logout")
         .deleteCookies("my-remember-me-cookie")
            .permitAll()
            .and()
        .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Add a filter to validate the tokens with every request
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

PersistentTokenRepository persistentTokenRepository(){
 JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl();
 tokenRepositoryImpl.setDataSource(dataSource);
 return tokenRepositoryImpl;
}

}

I am calling my service using the below code

    delete(userId: number) {
        debugger;
        return this.http.delete(`/api/v1/deleteUser/${userId}`);
    }

I am getting

Failed to load resource: the server responded with a status of 403 (Forbidden)

在此处输入图片说明

The question was based on this tutorial

The JwtRequestFilter.doFilterInternal() uses JwtUserDetailsService.loadUserByUsername(username) to set the user credentials upon successful validation of the token . The logic didnt set the GrantedAuthorities and resulted in authorization failures down stream.

Setting the GrantedAuthorities correctly , fixed the method level authorization issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM