Vaadin 7 + Spring Boot Security 处理 Access Dined 异常

Vaadin 7 + Spring Boot Security handle Access Dined exceptions

我有一个 Spring 服务方法,注释为 @PreAuthorize:

@Override
@PreAuthorize("hasAuthority('PERMISSION_CREATE_DECISION')")
public Decision createProduct(String name, String description, String url) 

当我尝试从未经授权的用户的代码访问此方法时,我收到 AccessDeniedException:

org.springframework.security.access.AccessDeniedException: Access is denied
    at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83)

那绝对没问题。

在这种情况下,我需要将该用户转发到应用程序登录页面。

如何在 Vaadin 7 + Spring 安全性中做到这一点?

在 UI class 中设置自定义 ErrorHandler,用于处理捕获 AccessDeniedException(在应用程序中的任何地方抛出)、使会话和重定向无效。

@SpringUI
public class CustomUI extends UI {

    @Override
    protected void init(final VaadinRequest request) {
        setErrorHandler(new CustomErrorHandler());
    }
}

public class CustomErrorHandler implements ErrorHandler {

    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
    @Override
    public void error(ErrorEvent event) {
        Throwable finalCause = getFinalCause(event.getThrowable());
        if (AccessDeniedException.class.isAssignableFrom(finalCause.getClass())) {
            // do everything you need
            UI.getCurrent().getSession().close();                   //close Vaadin session
            UI.getCurrent().getSession().getSession().invalidate(); //close Http session
            UI.getCurrent().getPage().setLocation("/login");        //redirect..
            UI.getCurrent().getNavigator().navigateTo("viewName");      //... or using navigator
            return;
        }

        DefaultErrorHandler.doDefault(event);
    }

    private Throwable getFinalCause(Throwable throwable) {
        while (throwable.getCause() != null) {
            throwable = throwable.getCause();
        }
        return throwable;
    }
}