【问题标题】:@PreAuthorize("hasRole('ROLE_ADMIN')") is throwing Forbidden@PreAuthorize("hasRole('ROLE_ADMIN')") 正在抛出 Forbidden
【发布时间】:2020-06-15 20:20:33
【问题描述】:

我正在使用@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 (禁止)

【问题讨论】:

  • 使用角色ROLE_ADMIN 验证(您的请求)将有助于/克服这个问题。 (用户/密码/角色分配/sso 令牌在哪里?)
  • 试试@PreAuthorize("hasRole('ADMIN')")Reference
  • @R.G @PreAuthorize("hasRole('ADMIN')") 也遇到同样的错误
  • 您是如何在应用程序中配置角色的?是ROLE_ADMIN
  • 是的,我已经配置了角色并且登录的人包含ROLE_ADMIN

标签: angular spring spring-boot spring-security


【解决方案1】:

这个问题是基于这个tutorial

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

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

【讨论】:

    猜你喜欢
    • 2011-07-10
    • 2020-06-12
    • 1970-01-01
    • 2013-10-19
    • 2013-08-14
    • 2021-09-12
    • 2020-06-24
    • 2015-12-09
    • 1970-01-01
    相关资源
    最近更新 更多