GraalVM Native Image 中的方法安全

尽管 方法安全 在 GraalVM Native Image 中受支持,但某些用例需要应用程序提供额外的提示。

使用 @PreAuthorize@PostAuthorize 注解

如果你有 UserDetailsAuthentication 类的自定义实现,使用 @PreAuthorize@PostAuthorize 注解需要额外的提示。

假设你有一个如下所示的 UserDetails 类的自定义实现,并且该实现由你的 UserDetailsService 返回

UserDetails 的自定义实现
public class CustomUserDetails implements UserDetails {

    private final String username;

    private final String password;

    private final Collection<? extends GrantedAuthority> authorities;

    public boolean isAdmin() {
        return this.authorities.contains(new SimpleGrantedAuthority("ROLE_ADMIN"));
    }

    // constructors, getters and setters
}

并且你想在 @PreAuthorize 注解中使用 isAdmin() 方法,如下所示

使用 isAdmin() 来保护方法
@PreAuthorize("principal?.isAdmin()")
public String hello() {
    return "Hello!";
}

请记住,你需要在你的配置类上添加 @EnableMethodSecurity 注解来启用方法安全注解。

如果你使用上述配置运行你的应用程序的 Native Image,当尝试调用 hello() 方法时,你会收到类似于以下的错误

failed: java.lang.IllegalArgumentException: Failed to evaluate expression 'principal?.isAdmin()' with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method isAdmin() cannot be found on type com.mypackage.CustomUserDetails

这意味着在 CustomUserDetails 类上找不到 isAdmin() 方法。这是因为 Spring Security 使用反射来调用 isAdmin() 方法,而 GraalVM Native Image 默认不支持反射。

为了解决这个问题,你需要给 GraalVM Native Image 提供提示,以允许对 CustomUserDetails#isAdmin() 方法进行反射。我们可以通过提供自定义提示来实现这一点。在本例中,我们将使用@RegisterReflectionForBinding 注解

你可能需要注册所有你想在 @PreAuthorize@PostAuthorize 注解中使用的类。

使用 @RegisterReflectionForBinding
@Configuration
@RegisterReflectionForBinding(CustomUserDetails.class)
public class MyConfiguration {
    //...
}

就是这样,现在你可以运行你的应用程序的 Native Image,它应该按预期工作。