Reputation: 2211
I have a Spring service method annotated with @PreAuthorize
:
@Override
@PreAuthorize("hasAuthority('PERMISSION_CREATE_DECISION')")
public Decision createProduct(String name, String description, String url)
When I try to access this method from code with not authorized user I'm receiving AccessDeniedException:
org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83)
that is absolutely fine.
in this case I need to forward this user to the application login page.
How to do it in Vaadin 7 + Spring Security ?
Upvotes: 1
Views: 375
Reputation: 168
In UI class set custom ErrorHandler that deals with catching AccessDeniedException (thrown anywhere in application), invalidating session and redirection.
@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;
}
}
Upvotes: 2