Access control

In this tutorial we will look into access control.

Basic access control

The application we’ve been building will inevitably need some administrative tools. Creation and deletion of users, for example, is generally something that we’d like to do during runtime. Let’s create a simple View for creating a new user:

Java

  1. package com.vaadin.cdi.tutorial;
  2. import java.util.concurrent.atomic.AtomicLong;
  3. import javax.inject.Inject;
  4. import com.vaadin.cdi.CDIView;
  5. import com.vaadin.data.Validator;
  6. import com.vaadin.data.fieldgroup.BeanFieldGroup;
  7. import com.vaadin.data.fieldgroup.FieldGroup.CommitEvent;
  8. import com.vaadin.data.fieldgroup.FieldGroup.CommitException;
  9. import com.vaadin.data.fieldgroup.FieldGroup.CommitHandler;
  10. import com.vaadin.navigator.View;
  11. import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
  12. import com.vaadin.ui.Button;
  13. import com.vaadin.ui.Button.ClickEvent;
  14. import com.vaadin.ui.Button.ClickListener;
  15. import com.vaadin.ui.CustomComponent;
  16. import com.vaadin.ui.Label;
  17. import com.vaadin.ui.VerticalLayout;
  18. @CDIView
  19. public class CreateUserView extends CustomComponent implements View {
  20. @Inject
  21. UserDAO userDAO;
  22. private static final AtomicLong ID_FACTORY = new AtomicLong(3);
  23. @Override
  24. public void enter(ViewChangeEvent event) {
  25. final VerticalLayout layout = new VerticalLayout();
  26. layout.setMargin(true);
  27. layout.setSpacing(true);
  28. layout.addComponent(new Label("Create new user"));
  29. final BeanFieldGroup<User> fieldGroup = new BeanFieldGroup<User>(
  30. User.class);
  31. layout.addComponent(fieldGroup.buildAndBind("firstName"));
  32. layout.addComponent(fieldGroup.buildAndBind("lastName"));
  33. layout.addComponent(fieldGroup.buildAndBind("username"));
  34. layout.addComponent(fieldGroup.buildAndBind("password"));
  35. layout.addComponent(fieldGroup.buildAndBind("email"));
  36. fieldGroup.getField("username").addValidator(new Validator() {
  37. @Override
  38. public void validate(Object value) throws InvalidValueException {
  39. String username = (String) value;
  40. if (username.isEmpty()) {
  41. throw new InvalidValueException("Username cannot be empty");
  42. }
  43. if (userDAO.getUserBy(username) != null) {
  44. throw new InvalidValueException("Username is taken");
  45. }
  46. }
  47. });
  48. fieldGroup.setItemDataSource(new User(ID_FACTORY.incrementAndGet(), "",
  49. "", "", "", "", false));
  50. final Label messageLabel = new Label();
  51. layout.addComponent(messageLabel);
  52. fieldGroup.addCommitHandler(new CommitHandler() {
  53. @Override
  54. public void preCommit(CommitEvent commitEvent) throws CommitException {
  55. }
  56. @Override
  57. public void postCommit(CommitEvent commitEvent) throws CommitException {
  58. userDAO.saveUser(fieldGroup.getItemDataSource().getBean());
  59. fieldGroup.setItemDataSource(new User(ID_FACTORY
  60. .incrementAndGet(), "", "", "", "", "", false));
  61. }
  62. });
  63. Button commitButton = new Button("Create");
  64. commitButton.addClickListener(new ClickListener() {
  65. @Override
  66. public void buttonClick(ClickEvent event) {
  67. try {
  68. fieldGroup.commit();
  69. messageLabel.setValue("User created");
  70. } catch (CommitException e) {
  71. messageLabel.setValue(e.getMessage());
  72. }
  73. }
  74. });
  75. layout.addComponent(commitButton);
  76. setCompositionRoot(layout);
  77. }
  78. }

CDIViewProvider checks the Views for a specific annotation, javax.annotation.security.RolesAllowed. You can get access to it by adding the following dependency to your pom.xml:

XML

  1. <dependency>
  2. <groupId>javax.annotation</groupId>
  3. <artifactId>javax.annotation-api</artifactId>
  4. <version>1.2-b01</version>
  5. </dependency>

Java

  1. @CDIView
  2. @RolesAllowed({ "admin" })
  3. public class CreateUserView extends CustomComponent implements View {

To add access control to our application we’ll need to have a concrete implementation of the AccessControl abstract class. Vaadin CDI comes bundled with a simple JAAS implementation, but configuring a JAAS security domain is outside the scope of this tutorial. Instead we’ll opt for a simpler implementation.

We’ll go ahead and alter our UserInfo class to include hold roles.

Java

  1. private List<String> roles = new LinkedList<String>();
  2. public void setUser(User user) {
  3. this.user = user;
  4. roles.clear();
  5. if (user != null) {
  6. roles.add("user");
  7. if (user.isAdmin()) {
  8. roles.add("admin");
  9. }
  10. }
  11. }
  12. public List<String> getRoles() {
  13. return roles;
  14. }

Let’s extend AccessControl and use our freshly modified UserInfo in it.

Java

  1. package com.vaadin.cdi.tutorial;
  2. import javax.enterprise.inject.Alternative;
  3. import javax.inject.Inject;
  4. import com.vaadin.cdi.access.AccessControl;
  5. @Alternative
  6. public class CustomAccessControl extends AccessControl {
  7. @Inject
  8. private UserInfo userInfo;
  9. @Override
  10. public boolean isUserSignedIn() {
  11. return userInfo.getUser() != null;
  12. }
  13. @Override
  14. public boolean isUserInRole(String role) {
  15. if (isUserSignedIn()) {
  16. for (String userRole : userInfo.getRoles()) {
  17. if (role.equals(userRole)) {
  18. return true;
  19. }
  20. }
  21. }
  22. return false;
  23. }
  24. @Override
  25. public String getPrincipalName() {
  26. if (isUserSignedIn()) {
  27. return userInfo.getUser().getUsername();
  28. }
  29. return null;
  30. }
  31. }

Note the @Alternative annotation. The JAAS implementation is set as the default, and we can’t have multiple default implementations. We’ll have to add our custom implementation to the beans.xml:

XML

  1. <beans>
  2. <alternatives>
  3. <class>com.vaadin.cdi.tutorial.UserGreetingImpl</class>
  4. <class>com.vaadin.cdi.tutorial.CustomAccessControl</class>
  5. </alternatives>
  6. <decorators>
  7. <class>com.vaadin.cdi.tutorial.NavigationLogDecorator</class>
  8. </decorators>
  9. </beans>

Now let’s add a button to navigate to this view.

ChatView:

Java

  1. private Layout buildUserSelectionLayout() {
  2. VerticalLayout layout = new VerticalLayout();
  3. layout.setWidth("100%");
  4. layout.setMargin(true);
  5. layout.setSpacing(true);
  6. layout.addComponent(new Label("Select user to talk to:"));
  7. for (User user : userDAO.getUsers()) {
  8. if (user.equals(userInfo.getUser())) {
  9. continue;
  10. }
  11. layout.addComponent(generateUserSelectionButton(user));
  12. }
  13. layout.addComponent(new Label("Admin:"));
  14. Button createUserButton = new Button("Create user");
  15. createUserButton.addClickListener(new ClickListener() {
  16. @Override
  17. public void buttonClick(ClickEvent event) {
  18. navigationEvent.fire(new NavigationEvent("create-user"));
  19. }
  20. });
  21. layout.addComponent(createUserButton);
  22. return layout;
  23. }

Everything seems to work fine, the admin is able to use this new feature to create a new user and the view is inaccessible to non-admins. An attempt to access the view without the proper authorization will currently cause an IllegalArgumentException. A better approach would be to create an error view and display that instead.

Java

  1. package com.vaadin.cdi.tutorial;
  2. import javax.inject.Inject;
  3. import com.vaadin.cdi.access.AccessControl;
  4. import com.vaadin.navigator.View;
  5. import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
  6. import com.vaadin.ui.Button;
  7. import com.vaadin.ui.Button.ClickEvent;
  8. import com.vaadin.ui.Button.ClickListener;
  9. import com.vaadin.ui.CustomComponent;
  10. import com.vaadin.ui.Label;
  11. import com.vaadin.ui.VerticalLayout;
  12. public class ErrorView extends CustomComponent implements View {
  13. @Inject
  14. private AccessControl accessControl;
  15. @Inject
  16. private javax.enterprise.event.Event<NavigationEvent> navigationEvent;
  17. @Override
  18. public void enter(ViewChangeEvent event) {
  19. VerticalLayout layout = new VerticalLayout();
  20. layout.setSizeFull();
  21. layout.setMargin(true);
  22. layout.setSpacing(true);
  23. layout.addComponent(new Label(
  24. "Unfortunately, the page you've requested does not exists."));
  25. if (accessControl.isUserSignedIn()) {
  26. layout.addComponent(createChatButton());
  27. } else {
  28. layout.addComponent(createLoginButton());
  29. }
  30. setCompositionRoot(layout);
  31. }
  32. private Button createLoginButton() {
  33. Button button = new Button("To login page");
  34. button.addClickListener(new ClickListener() {
  35. @Override
  36. public void buttonClick(ClickEvent event) {
  37. navigationEvent.fire(new NavigationEvent("login"));
  38. }
  39. });
  40. return button;
  41. }
  42. private Button createChatButton() {
  43. Button button = new Button("Back to the main page");
  44. button.addClickListener(new ClickListener() {
  45. @Override
  46. public void buttonClick(ClickEvent event) {
  47. navigationEvent.fire(new NavigationEvent("chat"));
  48. }
  49. });
  50. return button;
  51. }
  52. }

To use this we’ll modify our NavigationService to add the error view to the Navigator.

NavigationServiceImpl:

Java

  1. @Inject
  2. private ErrorView errorView;
  3. @PostConstruct
  4. public void initialize() {
  5. if (ui.getNavigator() == null) {
  6. Navigator navigator = new Navigator(ui, ui);
  7. navigator.addProvider(viewProvider);
  8. navigator.setErrorView(errorView);
  9. }
  10. }

We don’t really want the admin-only buttons to be visible to non-admin users. To programmatically hide them we can inject AccessControl to our view.

ChatView:

Java

  1. @Inject
  2. private AccessControl accessControl;
  3. private Layout buildUserSelectionLayout() {
  4. VerticalLayout layout = new VerticalLayout();
  5. layout.setWidth("100%");
  6. layout.setMargin(true);
  7. layout.setSpacing(true);
  8. layout.addComponent(new Label("Select user to talk to:"));
  9. for (User user : userDAO.getUsers()) {
  10. if (user.equals(userInfo.getUser())) {
  11. continue;
  12. }
  13. layout.addComponent(generateUserSelectionButton(user));
  14. }
  15. if(accessControl.isUserInRole("admin")) {
  16. layout.addComponent(new Label("Admin:"));
  17. Button createUserButton = new Button("Create user");
  18. createUserButton.addClickListener(new ClickListener() {
  19. @Override
  20. public void buttonClick(ClickEvent event) {
  21. navigationEvent.fire(new NavigationEvent("create-user"));
  22. }
  23. });
  24. layout.addComponent(createUserButton);
  25. }
  26. return layout;
  27. }

Some further topics

In the previous section we pruned the layout programmatically to prevent non-admins from even seeing the admin buttons. That was one way to do it. Another would be to create a custom component representing the layout, then create a producer for that component which would determine at runtime which version to create.

Sometimes there’s a need for a more complex custom access control implementations. You may need to use something more than Java Strings to indicate user roles, you may want to alter access rights during runtime. For those purposes we could extend the CDIViewProvider (with either the @Specializes annotation or @Alternative with a beans.xml entry) and override isUserHavingAccessToView(Bean<?> viewBean).