您的位置:首页 > 编程语言 > Java开发

关于Spring Boot下Spring Security权限访问设置@PreAuthorize("hasRole('ROLE_ADMIN')")没有用

2016-08-25 11:19 591 查看
承接上篇:Spring Security整合后post数据不了,403拒绝访问

前几天想要限制不同角色的访问权限,于是就直接使用:

@PreAuthorize("hasRole('ROLE_ADMIN')")


注解来标注一个实现类的方法上,但是其他权限依然可以访问 orz,于是我怀疑是放的位置不对,于是放在了Service接口里的方法上,也未果。于是直接放在Controller层的访问方法上,还是未果 ==|||

好了,上网查了一番:Spring Security @PreAuthorize 拦截无效

这篇文章刚好戳中要点:

没有设置开启prePostEnable=true;因为这个默认为false;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Bean
UserDetailsService customUserService() {
return new CustomUserService();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService());
}

@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/test","/test1").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage(RequestUrls.LoginUrl)
.failureUrl(RequestUrls.LoginUrl+"?error")
.permitAll()
.and()
.logout().permitAll();
}
}


如上,添加:

@EnableGlobalMethodSecurity(prePostEnabled=true)


@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
return super.authenticationManager();
}


以及:

@Autowired//注意这个方法是注入的
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService());
}


就酱紫~权限访问完美解决了!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐