Only allow button click with permission

Hi,
I am new to Vaadin. I did the tutorial and tested the login/security stuff. I wonder if it is possible to secure button clicks, for example.

Scenario: I have the user right X and page A is shown. On A is a button which I am only allowed to click if the user right Y is granted.

Maybe there is a tutorial which I could not find or anyone got a hint.

Thank you

Hello, I’m not sure which tutorial you are referring to, but there is this one for adding authentication and authorization to Vaadin app using Spring security: https://vaadin.com/learn/tutorials/securing-your-app-with-spring-security.

This is the part of this tutorial discussing authorization: https://vaadin.com/learn/tutorials/securing-your-app-with-spring-security/fine-grained-access-control.

Tarek Oraby:
Hello, I’m not sure which tutorial you are referring to, but there is this one for adding authentication and authorization to Vaadin app using Spring security: https://vaadin.com/learn/tutorials/securing-your-app-with-spring-security.

This is the part of this tutorial discussing authorization: https://vaadin.com/learn/tutorials/securing-your-app-with-spring-security/fine-grained-access-control.

Thanks for your answer. These are the two tutorials I did. It works fine.

But it is possible to use these @Secure for Components only? (Not for the whole page…)

I don’t think it possible to use @Secure on Components. What you can do, however, is to get the role of the current user, and display the components based on that.

To get the roles of the current user, you can use the following utility method:

public static Set<String> getAuthorities() {
	SecurityContext context = SecurityContextHolder.getContext();
	Object principal = context.getAuthentication().getPrincipal();
	if (principal instanceof UserDetails) {
		UserDetails userDetails = (UserDetails) context.getAuthentication().getPrincipal();
		Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
		return authorities.stream().map(e -> e.getAuthority()).collect(Collectors.toSet());
	}
	// Anonymous or no authentication.
	return null;
}

Then in your view, you can do something like the following

Set<String> authorities = getAuthorities();
if (authorities == null) {
	add(new Span("Only users with no authority will see me"));
} else {
	if (authorities.contains("ROLE_User")) {
		add(new Span("Only users with ROLE_User will see me "));
	}
	if (authorities.contains("ROLE_Admin")) {
		add(new Span("Only users with ROLE_Admin will see me "));
	}
}

Thank you. This is what I needed.