首页 > 解决方案 > 如何实现 Spring Method 级别的安全性

问题描述

我想实现 Spring Method 级别的安全性。为此,我所做的是

@Configuration
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig  extends WebSecurityConfigurerAdapter{
@Autowired
private AccessDeniedHandler accessDeniedHandler;

@Autowired
private AdminPortalAuthProvider authProvider;

@Autowired
private AdminWebAuthDetailsSource authenticationDetailsSource;

@Autowired
AdminAuthSuccessHandler successHandler;

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
    .csrf().csrfTokenRepository(csrfTokenRepository()).and()
        .antMatcher("/admin/**")
        .authorizeRequests().antMatchers("/admin/registration","/admin/setPassword").anonymous()
        .antMatchers("/admin/setPass").permitAll()
        .anyRequest().authenticated()
        .and()
        .formLogin()
            .authenticationDetailsSource(authenticationDetailsSource)
            .usernameParameter("username")
            .passwordParameter("password")
            .loginPage("/admin/login")
            .defaultSuccessUrl("/admin/home")
            .successHandler(successHandler)
            .permitAll()
         .and()
            .logout()
            .logoutUrl("/admin/logout")
            .invalidateHttpSession(true)
            .permitAll()

         .and()
            .exceptionHandling().accessDeniedHandler(accessDeniedHandler)
        .and()
            .authenticationProvider(authProvider)
         .addFilterAfter(new CsrfHeaderFilter(), CsrfFilter.class)
         .addFilterAfter(new CustomSecurityFilter(),BasicAuthenticationFilter.class)
         .headers().xssProtection().and().frameOptions().sameOrigin()
        .cacheControl().and().contentTypeOptions();   

}


private CsrfTokenRepository csrfTokenRepository() {
    HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
    repository.setHeaderName("X-XSRF-TOKEN");
    return repository;
}

@Override
public void configure(WebSecurity web) throws Exception {
  web.ignoring().antMatchers("/js/**","/css/**","/img/**","/customjs/**","/fonts/**","/lib/**","/icons-reference/**","/admin/registration/**","/admin/customer/payment-invoice-pg-post");
}

}

我正在使用@PreAuthorize("hasRole('ROLE_ADMIN')"))

在方法上,但它仍然无法正常工作......任何人都可以帮助我......

因为我被要求将我的 securityConfig 代码放在所有关于 url security 的地方,所以我在这里编辑了我的问题......

标签: javaspringspring-securityspring-aop

解决方案


我建议尝试使用GlobalMethodSecurityConfiguration类。

 @Configuration
 @EnableGlobalMethodSecurity(
  prePostEnabled = true)
 public class MethodSecurityConfig 
  extends GlobalMethodSecurityConfiguration {
 }

推荐阅读