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 "));
}
}