Spring 安全性自定义身份验证过滤器和授权



我已经实现了一个自定义身份验证过滤器,它工作得很好。我使用外部身份提供程序,并在设置会话并将身份验证对象添加到安全上下文后重定向到最初请求的 URL。

安全配置

@EnableWebSecurity(debug = true)
@Configuration
class SecurityConfig extends WebSecurityConfigurerAdapter {
// this is needed to pass the authentication manager into our custom security filter
@Bean
@Override
AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean()
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
//.antMatchers("/admin/test").hasRole("METADATA_CURATORZ")
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(new CustomSecurityFilter(authenticationManagerBean()), UsernamePasswordAuthenticationFilter.class)
}
}

筛选逻辑

目前,我的自定义过滤器(一旦确认身份(只是对角色进行硬编码:

SimpleGrantedAuthority myrole = new SimpleGrantedAuthority("METADATA_CURATORZ")
return new PreAuthenticatedAuthenticationToken(securityUser, null, [myrole])

然后,该身份验证对象(上面返回(在重定向到所需的端点之前被添加到我的 SecurityContext 中:

SecurityContextHolder.getContext().setAuthentication(authentication)

控制器端点

@RequestMapping(path = '/admin/test', method = GET, produces = 'text/plain')
String test(HttpServletRequest request) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication()
String roles = auth.getAuthorities()
return "roles: ${roles}"
}

然后,此端点在浏览器中生成以下响应:

"角色:[METADATA_CURATORZ]">

伟大。因此,我的身份验证和将角色应用于我的用户工作得很好。

现在,如果我从安全配置中取消注释此行:

//.antMatchers("/admin/test").hasRole("METADATA_CURATORZ")

我无法再访问该资源并获得 403 - 即使我们已经证明角色已设置。

这对我来说似乎完全是荒谬和破碎的,但我不是 Spring 安全专家。

我可能错过了一些非常简单的东西。有什么想法吗?

我有一些问题:

  • 是否需要将我的自定义筛选器放在特定的内置筛选器之前,以确保在执行该筛选器后执行授权步骤?
  • 在请求周期中,何时进行 antMatcher/hasRole 检查?
  • 是否需要更改我在安全配置链中调用的内容的顺序,以及我应该如何理解当前编写的配置?它显然没有做我认为应该做的事情。

我的自定义筛选器是否需要放置在特定的内置筛选器之前,以确保在执行该筛选器后执行授权步骤?

您的过滤器必须在FilterSecurityInterceptor之前,因为这是进行授权和身份验证的地方。此筛选器是最后一个调用的筛选器之一。

现在至于过滤器的最佳位置在哪里,这真的取决于。例如,你确实希望筛选器位于AnonymousAuthenticationFilter之前,因为否则,在调用筛选器时,未经身份验证的用户将始终使用AnonymousAuthenticationToken"进行身份验证"。

您可以在FilterComparator中查看过滤器的默认顺序。AbstractPreAuthenticatedProcessingFilter几乎与您正在做的事情相对应 - 并且它按过滤器的顺序放置可以让您了解可以放置的位置。无论如何,您的过滤器的顺序应该没有问题。

在请求周期中,何时进行 antMatcher/hasRole 检查?

所有这些都发生在FilterSecurityInterceptor,更准确地说,发生在它的父AbstractSecurityInterceptor中:

protected InterceptorStatusToken beforeInvocation(Object object) {
Collection<ConfigAttribute> attributes = this.obtainSecurityMetadataSource()
.getAttributes(object);
if (attributes == null || attributes.isEmpty()) {
...
}
...
Authentication authenticated = authenticateIfRequired();
// Attempt authorization
try {
this.accessDecisionManager.decide(authenticated, object, attributes);
}
catch (AccessDeniedException accessDeniedException) {
...
throw accessDeniedException;
}

额外信息:本质上,FilterSecurityInterceptor有一个包含Map<RequestMatcher, Collection<ConfigAttribute>>ExpressionBasedFilterInvocationSecurityMetadataSource。在运行时,将根据Map检查您的请求,以查看是否有任何RequestMatcher键匹配。如果是,则Collection<ConfigAttribute>被传递给AccessDecisionManager,最终授予或拒绝访问。默认AccessDecisionManagerAffirmativeBased,包含处理ConfigAttribute集合并通过反射针对使用Authentication初始化的SecurityExpressionRoot对象调用与您的"hasRole('METADATA_CURATORZ')"对应的SpelExpression(通常是WebExpressionVoter(。

是否需要更改我在安全配置链中调用的内容的顺序,以及我应该如何理解当前编写的配置?它显然没有做我认为应该做的事情。

不,您的过滤器应该没有任何问题。作为旁注,除了configure(HttpSecurity http)方法中的内容外,您扩展的WebSecurityConfigurerAdapter还有一些默认值:

http
.csrf().and()
.addFilter(new WebAsyncManagerIntegrationFilter())
.exceptionHandling().and()
.headers().and()
.sessionManagement().and()
.securityContext().and()
.requestCache().and()
.anonymous().and()
.servletApi().and()
.apply(new DefaultLoginPageConfigurer<>()).and()
.logout();

如果您想确切了解它们的作用以及它们添加了哪些过滤器,可以查看HttpSecurity

问题所在

执行以下操作时:

.authorizeRequests()
.antMatchers("/admin/test").hasRole("METADATA_CURATORZ")

。搜索的角色是"ROLE_METADATA_CURATORZ"。为什么?ExpressionUrlAuthorizationConfigurer的静态hasRole(String role)方法最终处理"METADATA_CURATORZ"

if (role.startsWith("ROLE_")) {
throw new IllegalArgumentException(
"role should not start with 'ROLE_' since it is automatically inserted. Got '"
+ role + "'");
}
return "hasRole('ROLE_" + role + "')";
}

所以你的授权表达式变得"hasRole('ROLE_METADATA_CURATORZ'",这最终调用了方法hasRole('ROLE_METADATA_CURATORZ')SecurityExpressionRoot,而该方法又搜索Authentication权限中的角色ROLE_METADATA_CURATORZ

解决方案

改变

SimpleGrantedAuthority myrole = new SimpleGrantedAuthority("METADATA_CURATORZ");

自:

SimpleGrantedAuthority myrole = new SimpleGrantedAuthority("ROLE_METADATA_CURATORZ");

最新更新