SpringSecurity(Authorization Events)

发布于:2024-07-11 ⋅ 阅读:(25) ⋅ 点赞:(0)

Authorization Events

对于每个被拒绝的授权,都会激发一个 AuthorizationDeniedEvent。此外,还可以为授予的授权激发 AuthorizationGrantedEvent。

若要侦听这些事件,必须首先发布 AuthorizationEventPublisher。

Spring Security 的 SpringAuthorizationEventPublisher 可能会做得很好。它使用 Spring 的 ApplicationEventPublisher 发布授权事件:

@Bean
public AuthorizationEventPublisher authorizationEventPublisher
        (ApplicationEventPublisher applicationEventPublisher) {
    return new SpringAuthorizationEventPublisher(applicationEventPublisher);
}

然后,您可以使用 Spring 的@EventListener 支持:

@Component
public class AuthenticationEvents {

    @EventListener
    public void onFailure(AuthorizationDeniedEvent failure) {
		// ...
    }
}

Authorization Granted Events

因为 AuthorizationGrantedEvents 有可能非常嘈杂,所以默认情况下不发布它们。

事实上,发布这些事件可能需要您自己的一些业务逻辑,以确保应用程序不会被嘈杂的授权事件淹没。

您可以创建自己的事件发布者来筛选成功事件。例如,下面的发布者只在需要 ROLE _ ADMIN 的地方发布授权:

@Component
public class MyAuthorizationEventPublisher implements AuthorizationEventPublisher {
    private final ApplicationEventPublisher publisher;
    private final AuthorizationEventPublisher delegate;

    public MyAuthorizationEventPublisher(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
        this.delegate = new SpringAuthorizationEventPublisher(publisher);
    }

    @Override
    public <T> void publishAuthorizationEvent(Supplier<Authentication> authentication,
            T object, AuthorizationDecision decision) {
        if (decision == null) {
            return;
        }
        if (!decision.isGranted()) {
            this.delegate.publishAuthorizationEvent(authentication, object, decision);
            return;
        }
        if (shouldThisEventBePublished(decision)) {
            AuthorizationGrantedEvent granted = new AuthorizationGrantedEvent(
                    authentication, object, decision);
            this.publisher.publishEvent(granted);
        }
    }

    private boolean shouldThisEventBePublished(AuthorizationDecision decision) {
        if (!(decision instanceof AuthorityAuthorizationDecision)) {
            return false;
        }
        Collection<GrantedAuthority> authorities = ((AuthorityAuthorizationDecision) decision).getAuthorities();
        for (GrantedAuthority authority : authorities) {
            if ("ROLE_ADMIN".equals(authority.getAuthority())) {
                return true;
            }
        }
        return false;
    }
}