本篇内容主要讲解“Spring Security权限控制的接口怎么实现”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Spring Security权限控制的接口怎么实现”吧!
认证过程中会一并获得用户权限,Authentication#getAuthorities
接口方法提供权限,认证过后即是鉴权,Spring Security使用GrantedAuthority
接口代表权限。早期版本在FilterChain
中使用FilterSecurityInterceptor
中执行鉴权过程,现使用AuthorizationFilter
执行,开始执行顺序两者一致,此外,Filter
中具体实现也由 AccessDecisionManager
+ AccessDecisionVoter
变为 AuthorizationManager
本文关注新版本的实现:AuthorizationFilter
和AuthorizationManager
。
AuthorizationManager
最常用的实现类为RequestMatcherDelegatingAuthorizationManager
,其中会根据你的配置生成一系列RequestMatcherEntry
,每个entry中包含一个匹配器RequestMatcher
和泛型类被匹配对象。
UML类图结构如下:
另外,对于 method security ,实现方式主要为AOP+Spring EL,常用权限方法注解为:
@EnableMethodSecurity
@PreAuthorize
@PostAuthorize
@PreFilter
@PostFilter
@Secured
这些注解可以用在controller方法上用于权限控制,注解中填写Spring EL表述权限信息。这些注解一起使用时的执行顺序由枚举类AuthorizationInterceptorsOrder
控制:
public enum AuthorizationInterceptorsOrder { FIRST(Integer.MIN_VALUE), /** * {@link PreFilterAuthorizationMethodInterceptor} */ PRE_FILTER, PRE_AUTHORIZE, SECURED, JSR250, POST_AUTHORIZE, /** * {@link PostFilterAuthorizationMethodInterceptor} */ POST_FILTER, LAST(Integer.MAX_VALUE); ... }
而这些权限注解的提取和配置主要由org.springframework.security.config.annotation.method.configuration
包下的几个配置类完成:
PrePostMethodSecurityConfiguration
SecuredMethodSecurityConfiguration
等
权限配置可以通过两种方式配置:
SecurityFilterChain
配置类配置
@EnableMethodSecurity
开启方法上注解配置
下面是关于SecurityFilterChain的权限配置,以及method security使用
@Configuration // 其中prepostEnabled默认true,其他注解配置默认false,需手动改为true @EnableMethodSecurity(securedEnabled = true) @RequiredArgsConstructor public class SecurityConfig { // 白名单 private static final String[] AUTH_WHITELIST = ... @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { // antMatcher or mvcMatcher http.authorizeHttpRequests() .antMatchers(AUTH_WHITELIST).permitAll() // hasRole中不需要添加 ROLE_前缀 // ant 匹配 /admin /admin/a /admin/a/b 都会匹配上 .antMatchers("/admin/**").hasRole("ADMIN") .anyRequest().authenticated(); // denyAll慎用 // .anyRequest().denyAll(); // http.authorizeHttpRequests() // .mvcMatchers(AUTH_WHITELIST).permitAll() // // 效果同上 // .mvcMatchers("/admin").hasRole("ADMIN") // .anyRequest().denyAll(); } }
以@PreAuthorize
为例,在controller方法上使用:
@Api("user") @RestController @RequestMapping("/user") @RequiredArgsConstructor public class UserController { /** * {@link EnableMethodSecurity} 注解必须配置在配置类上<br/> * {@link PreAuthorize}等注解中表达式使用 Spring EL * @return */ @PreAuthorize("hasRole('ADMIN')") @GetMapping("/admin") public ResponseEntity<Map<String, Object>> admin() { return ResponseEntity.ok(Collections.singletonMap("msg","u r admin")); } }
AuthorizationFilter
public class AuthorizationFilter extends OncePerRequestFilter { // 在配置类中默认实现为 RequestMatcherDelegatingAuthorizationManager private final AuthorizationManager<HttpServletRequest> authorizationManager; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 委托给AuthorizationManager AuthorizationDecision decision = this.authorizationManager.check(this::getAuthentication, request); if (decision != null && !decision.isGranted()) { throw new AccessDeniedException("Access Denied"); } filterChain.doFilter(request, response); } }
来看看AuthorizationManager
默认实现RequestMatcherDelegatingAuthorizationManager
:
public final class RequestMatcherDelegatingAuthorizationManager implements AuthorizationManager<HttpServletRequest> { // http.authorizeHttpRequests().antMatchers(AUTH_WHITELIST)... // SecurityFilterChain中每配置一项就会增加一个Entry // RequestMatcherEntry包含一个RequestMatcher和一个待鉴权对象,这里是AuthorizationManager private final List<RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>>> mappings; ... @Override public AuthorizationDecision check(Supplier<Authentication> authentication, HttpServletRequest request) { for (RequestMatcherEntry<AuthorizationManager<RequestAuthorizationContext>> mapping : this.mappings) { RequestMatcher matcher = mapping.getRequestMatcher(); MatchResult matchResult = matcher.matcher(request); if (matchResult.isMatch()) { AuthorizationManager<RequestAuthorizationContext> manager = mapping.getEntry(); return manager.check(authentication, new RequestAuthorizationContext(request, matchResult.getVariables())); } } return null; } }
总的实现基于 AOP + Spring EL
以案例中 @PreAuthorize
注解的源码为例
PrePostMethodSecurityConfiguration
@Configuration(proxyBeanMethods = false) @Role(BeanDefinition.ROLE_INFRASTRUCTURE) final class PrePostMethodSecurityConfiguration { private final AuthorizationManagerBeforeMethodInterceptor preAuthorizeAuthorizationMethodInterceptor; private final PreAuthorizeAuthorizationManager preAuthorizeAuthorizationManager = new PreAuthorizeAuthorizationManager(); private final DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler(); ... @Autowired PrePostMethodSecurityConfiguration(ApplicationContext context) { // 设置 Spring EL 解析器 this.preAuthorizeAuthorizationManager.setExpressionHandler(this.expressionHandler); // 拦截@PreAuthorize方法 this.preAuthorizeAuthorizationMethodInterceptor = AuthorizationManagerBeforeMethodInterceptor .preAuthorize(this.preAuthorizeAuthorizationManager); ... } ... }
AuthorizationManagerBeforeMethodInterceptor
基于AOP实现
public final class AuthorizationManagerBeforeMethodInterceptor implements Ordered, MethodInterceptor, PointcutAdvisor, AopInfrastructureBean { /** * 调用起点 */ public static AuthorizationManagerBeforeMethodInterceptor preAuthorize() { // 针对 @PreAuthorize注解提供的AuthorizationManager为PreAuthorizeAuthorizationManager return preAuthorize(new PreAuthorizeAuthorizationManager()); } /** * 初始化,创建基于@PreAuthorize注解的aop方法拦截器 * Creates an interceptor for the {@link PreAuthorize} annotation * @param authorizationManager the {@link PreAuthorizeAuthorizationManager} to use * @return the interceptor */ public static AuthorizationManagerBeforeMethodInterceptor preAuthorize( PreAuthorizeAuthorizationManager authorizationManager) { AuthorizationManagerBeforeMethodInterceptor interceptor = new AuthorizationManagerBeforeMethodInterceptor( AuthorizationMethodPointcuts.forAnnotations(PreAuthorize.class), authorizationManager); interceptor.setOrder(AuthorizationInterceptorsOrder.PRE_AUTHORIZE.getOrder()); return interceptor; } ... // 实现MethodInterceptor方法,在调用实际方法是会首先触发这个 @Override public Object invoke(MethodInvocation mi) throws Throwable { // 先鉴权 attemptAuthorization(mi); // 后执行实际方法 return mi.proceed(); } private void attemptAuthorization(MethodInvocation mi) { // 判断, @PreAuthorize方法用的manager就是 // PreAuthorizeAuthorizationManager // 是通过上面的static类构造的 AuthorizationDecision decision = this.authorizationManager.check(AUTHENTICATION_SUPPLIER, mi); if (decision != null && !decision.isGranted()) { throw new AccessDeniedException("Access Denied"); } ... } static final Supplier<Authentication> AUTHENTICATION_SUPPLIER = () -> { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication == null) { throw new AuthenticationCredentialsNotFoundException( "An Authentication object was not found in the SecurityContext"); } return authentication; }; }
针对@PreAuthorize
方法用的manager就是 PreAuthorizeAuthorizationManager#check
,下面来看看
PreAuthorizeAuthorizationManager
public final class PreAuthorizeAuthorizationManager implements AuthorizationManager<MethodInvocation> { private final PreAuthorizeExpressionAttributeRegistry registry = new PreAuthorizeExpressionAttributeRegistry(); private MethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler(); @Override public AuthorizationDecision check(Supplier<Authentication> authentication, MethodInvocation mi) { // 获取方法上@PreAuthorize注解中的Spring EL 表达式属性 ExpressionAttribute attribute = this.registry.getAttribute(mi); if (attribute == ExpressionAttribute.NULL_ATTRIBUTE) { return null; } // Spring EL 的 context EvaluationContext ctx = this.expressionHandler.createEvaluationContext(authentication.get(), mi); // 执行表达式中结果, 会执行SecurityExpressionRoot类中对应方法。涉及Spring EL执行原理,pass boolean granted = ExpressionUtils.evaluateAsBoolean(attribute.getExpression(), ctx); // 返回结果 return new ExpressionAttributeAuthorizationDecision(granted, attribute); } }
到此,相信大家对“Spring Security权限控制的接口怎么实现”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。