簡體   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