首页 > 解决方案 > 403 访问被拒绝 Spring Security 每次

问题描述

对于每个具有模式 /admin 的请求,我都会收到 403 我只需要将 /admin 限制为管理员角色。

失败的方法:

  1. 尝试在控制器上使用@PreAuthorize(hasRole('ADMIN'))@PreAuthorize(hasRole('ROLE_ADMIN'))但没有运气。
  2. 尝试@PreAuthorize从控制器中删除并使用 hasRole 在下面的类中添加模式但没有运气

下面是类扩展WebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    AuthenticationEntryPoint authenticationEntryPoint;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .and()
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
            .authorizeRequests()

                .antMatchers(HttpMethod.OPTIONS).permitAll()
              .antMatchers(HttpMethod.GET,"/admin/**").hasAnyRole("ADMIN","ADMIN_TENANT")
                .anyRequest().authenticated()
                .and()
            .logout()
                .permitAll()
                .and()
            .csrf()
                .disable();
        httpSecurity.
            addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);

        httpSecurity.
            headers().cacheControl().disable();
    }

已经尝试过类似问题中提到的解决方案,但没有运气。所以请不要将其标记为重复。

标签: javaspring-bootspring-securityspring-aop

解决方案


我类似的 Git 项目这里

    // Config to check if already active
    http.authorizeRequests()
    .and() 
    .rememberMe()
    .tokenRepository(new JdbcTokenRepositoryImpl().setDataSource(//datasource_name) )
     .tokenValiditySeconds(//TimeInterval in sec); 

}

推荐阅读