Spring Security,方法安全注释(@Secured)不起作用(java config) [英] Spring Security, Method Security annotation (@Secured ) is not working (java config)

查看:547
本文介绍了Spring Security,方法安全注释(@Secured)不起作用(java config)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用@Secured("ADMIN")(没有任何XML,只有Java配置,Spring Boot)来设置方法安全注释.但是无法通过角色进行访问.

I am trying to set up a method security annotation using @Secured("ADMIN") (without any XML, only java config, Spring Boot). But access via roles does not work.

安全配置:

@Configuration
@EnableWebSecurity
public class AppSecurityConfiguration extends WebSecurityConfigurerAdapter{

.....

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/api/**").fullyAuthenticated().and()
                .addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }

.....

}

我想限制对控制器方法的访问:

I want restrict access to the method of the controller:

@RestController
@RequestMapping("/api/groups")
public class GroupController {

    @Autowired
    private GroupService groupService;

    @Secured("ADMIN")
    @RequestMapping
    public List<Group> list() {
        return groupService.findAll();
    }

}

通过url限制访问正在起作用,

Restrict access by the url is working, with:

.antMatchers("/api/**").hasAuthority("ADMIN")

也许我忘记指定要按角色进行限制了吗?

Maybe I forgot to specify that I want restrict by roles?

UPD: 根据规则,在控制器层或服务层中@PreAuthorize("hasRole('ADMIN')")必须在哪一层?

UPD: By the rules, At what layer must be @PreAuthorize("hasRole('ADMIN')") in Controller layer or in Service layer?

推荐答案

此问题已解决.

我添加@EnableGlobalMethodSecurity(prePostEnabled = true)

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

然后在控制器中,我将@Secured("ADMIN")更改为@PreAuthorize("hasRole('ADMIN')")

And in controller i changed @Secured("ADMIN") to @PreAuthorize("hasRole('ADMIN')")

这篇关于Spring Security,方法安全注释(@Secured)不起作用(java config)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆