繁体   English   中英

@PreAuthorize("hasRole('ROLE_ADMIN')") 正在抛出 Forbidden

[英]@PreAuthorize("hasRole('ROLE_ADMIN')") is throwing Forbidden

我正在使用@PreAuthorize("hasRole('ROLE_ADMIN')")来限制方法访问仅限于管理员,因为我编写了以下方法

@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((""));
        }

}

我的配置调用如下

@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;
}

}

我正在使用以下代码调用我的服务

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

我正进入(状态

加载资源失败:服务器响应状态为 403(禁止)

在此处输入图片说明

问题基于本教程

JwtRequestFilter.doFilterInternal()使用JwtUserDetailsService.loadUserByUsername(username)在成功验证令牌后设置用户凭据。 该逻辑没有设置GrantedAuthorities并导致下游授权失败。

正确设置 GrantedAuthorities ,修复了方法级别的授权问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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