在之前的博客中,我们深入揭秘了 Apollo 的配置更新机制和环境隔离特性。今天,我们的关注点将转向 Apollo 服务端的权限管理,探讨其具体实现方式。
Apollo服务端权限是基于Spring Security组件来实现的,实现的是方法级别的权限。核心是@PreAuthorize 注解,用于在方法调用之前进行权限验证,接下来我们让我们逐步揭秘。
@PreAuthorize注解介绍
@PreAuthorize 注解用于在方法执行之前基于表达式对用户进行权限验证。支持 Spring Expression Language(SpEL)表达式,常用的表达式包括:
- hasRole(‘ROLE_NAME’): 用户是否具有指定的角色。
- hasAuthority(‘AUTHORITY_NAME’): 用户是否具有指定的权限。
- principal: 当前认证用户的主体信息。
- #parameterName: 方法参数,可以在表达式中使用方法参数。
@PreAuthorize的实现细节
下面深入探讨 @PreAuthorize 的实现细节。
1. 启用方法安全功能
要使用 @PreAuthorize,首先需要在项目中启用全局方法安全性,通过配置类中的 @EnableGlobalMethodSecurity 注解实现。
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter {
public static final String USER_ROLE = "user";
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().sameOrigin();
http.authorizeRequests()
.antMatchers(BY_PASS_URLS).permitAll()
.antMatchers("/**").hasAnyRole(USER_ROLE);