本文来说下Spring Boot+Spring Security:基于内存的角色授权
概述
需求缘起
之前我们基于内存的方式,构建了两个账号admin和user,对于这两个账号在实际项目中会有不同的角色,比如管理员角色和普通用户角色,对于不同的角色,那么允许访问的方法会不一样。
编码思路
对于不同角色具有不同方法的权限的问题,主要需要思考几个点:
如何给指定的用户指定角色
通过AuthenticationManagerBuilder的roles()方法,就可以指定角色,示例代码:
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("123456"))
.roles("beijingAdmin","shanghaiAdmin");
上面的示例中指定了用户admin,具有beijingAdmin,shanghaiAdmin的角色。
如何开启方法级别安全控制
想要开启Spring方法级安全,你需要在已经添加了@Configuration注解的类上再添加@EnableGlobalMethodSecurity注解即可。
如何配置方法级别的权限控制
使用注解@PreAuthorize(“hasAnyRole(‘admin’)”)即可指定访问级别的角色。
基于内存的角色授权
这里基于上一篇文章进行编码。
为用户配置角色
通过AuthenticationManagerBuilder的roles()方法分配角色:
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
/*
* 配置为从内存中进行加载认证信息.
* 这里配置了两个用户 admin和user
*/
auth.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("123456"))
.roles("admin");
auth.inMemoryAuthentication()
.withUser("user")
.password(passwordEncoder().encode("123456"))
.roles("normal");
}
开启Spring方法级安全
想要开启Spring方法级安全,你需要在已经添加了@Configuration注解的类上再添加@EnableGlobalMethodSecurity注解:
(1)prePostEnabled :决定Spring Security的前注解是否可[@PreAuthorize,@PostAuthorize,…]
(2)secureEnabled : 决定是否Spring Security的保障注解 [@Secured] 是否可用。
(3)jsr250Enabled :决定 JSR-250 annotations 注解[@RolesAllowed…] 是否可用。
我们这里在WebSecurityConfig进行添加配置:
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
}
说明:只有添加了@EnableGlobalMethodSecurity(prePostEnabled=true)之后,@PreAuthorize(“hasAnyRole(‘admin’)”)才能生效。
配置方法级拥有的角色
我们在HelloController添加两个方法,使用注解@PreAuthorize指定访问该方法需要的角色:
package cn.wideth.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/hello")
@Api(description = "SpringSecurity测试", tags = "SpringSecurity")
public class HelloController {
@GetMapping("/helloAdmin")
@PreAuthorize("hasAnyRole('admin')")
@ApiOperation(value = "admin用户权限", notes = "admin用户权限")
public String helloAdmin() {
return "Hello,admin";
}
@GetMapping("/helloUser")
@PreAuthorize("hasAnyRole('admin','normal')")
@ApiOperation(value = "admin和normal用户权限", notes = "admin和normal用户权限")
public String helloUser() {
return "Hello,user";
}
}
测试角色
到这里就可以启动测试下:
我这里分别使用不同的用户名密码来测试,直接在swagger中调用接口,看接口是否可以通过。
admin/123456
/hello/helloAdmin和/hello/helloUser都可以通过
user/123456
/hello/helloAdmin不可以通过,/hello/helloUser都可以通过
本文小结
本文比较详细的介绍了Spring Security基于内存的角色授权。