Spring Security 注解

Spring Security 注解

需求缘起

在之前的章节中我们介绍过通过注解的方式进行权限的控制了,这里再详细的讲解下方法级安全的几个注解。

一、注解式方法级安全开启

需要在WebSecuirtyConfig添加配置:

@Configuration@EnableWebSecurity //启用Spring Security.////会拦截注解了@PreAuthrize注解的配置.@EnableGlobalMethodSecurity(prePostEnabled=true)public class WebSecurityConfig extends WebSecurityConfigurerAdapter{}

二、允许的注解

这里主要@PreAuthorize, @PostAuthorize, @Secured这三个注解可以使用。

2.1 @Secured

当@EnableGlobalMethodSecurity(securedEnabled=true)的时候,@Secured可以使用:

@GetMapping("/helloUser")@Secured({"ROLE_normal","ROLE_admin"})public String helloUser() { return "hello,user";}

说明:拥有normal或者admin角色的用户都可以方法helloUser()方法。另外需要注意的是这里匹配的字符串需要添加前缀“ROLE_“。

如果我们要求,只有同时拥有admin & noremal的用户才能方法helloUser()方法,这时候@Secured就无能为力了。

2.2 @PreAuthorize

Spring的 @PreAuthorize/@PostAuthorize 注解更适合方法级的安全,也支持Spring 表达式语言,提供了基于表达式的访问控制。

当@EnableGlobalMethodSecurity(prePostEnabled=true)的时候,@PreAuthorize可以使用:

@GetMapping("/helloUser")@PreAuthorize("hasAnyRole('normal','admin')")public String helloUser() { return "hello,user";}

说明:拥有normal或者admin角色的用户都可以方法helloUser()方法。

此时如果我们要求用户必须同时拥有normal和admin的话,那么可以这么编码:

@GetMapping("/helloUser")@PreAuthorize("hasRole('normal') AND hasRole('admin')") public String helloUser() { return "hello,user";}

此时如果使用user/123登录的话,就无法访问helloUser()的方法了。

2.3 @PostAuthorize

@PostAuthorize 注解使用并不多,在方法执行后再进行权限验证,适合验证带有返回值的权限,Spring EL 提供 返回对象能够在表达式语言中获取返回的对象returnObject。

当@EnableGlobalMethodSecurity(prePostEnabled=true)的时候,@PostAuthorize可以使用:

@GetMapping("/helloUser")@PostAuthorize(" returnObject!=null && returnObject.username == authentication.name")public User helloUser() { Object pricipal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User user; if("anonymousUser".equals(pricipal)) { user = null; }else { user = (User) pricipal; } return user;}

这三个最常用也就是@PreAuthorize这个注解了,在使用中主要是配合Spring EL表达式。

🎯 相关推荐

手机存储根目录在哪里?不同手机查找方法汇总
365bet进入官网

手机存储根目录在哪里?不同手机查找方法汇总

📅 09-09 👁️ 7553
原神的水晶怎么挖?矿物分布与高效采集路线
365体育在哪下载

原神的水晶怎么挖?矿物分布与高效采集路线

📅 08-13 👁️ 6259
14岁男生多久可以射精一次
365bet进入官网

14岁男生多久可以射精一次

📅 08-16 👁️ 997
勇猛的信仰头冠
365bet进入官网

勇猛的信仰头冠

📅 08-24 👁️ 2349
建筑电气接地的基本概念:接地分类和接地作用,是电气学者必备的
让我们来欣赏一下动物们那些奇葩的睡姿!
365bet足彩网上投注

让我们来欣赏一下动物们那些奇葩的睡姿!

📅 08-15 👁️ 9181