Difference between revisions of "Scout/Tutorial/3.9/Minicrm/Permissions"

From Eclipsepedia

< Scout‎ | Tutorial‎ | 3.9‎ | Minicrm
Jump to: navigation, search
Line 18: Line 18:
This chapter assumes that you're pretty proficient at creating tables, forms and services. No more hand-holding. :)
This chapter assumes that you're pretty proficient at creating tables, forms and services. No more hand-holding. :)
== PermissionService ==
Until {{Bug|410625}} is solved, we need to register a PermissionService that will find the permissions we have created in the previous steps of the MiniCrm tutorial.
Select "Services" under the server node in the project explorer and open the "New Service..." wizard.
Provide a name (for example <code>MinicrmPermissionService</code>), and a subpackage name (for example <code>services.common.security</code>). Click Next. In the second step untick all items in shared and client. We want to create a server only service.
Open the new class, and replace the generated code with this implementation:
<source lang="java">
* Custom Permission Service, that accept all *Permission classes.
* Workaround for Bug 410561
* https://bugs.eclipse.org/bugs/show_bug.cgi?id=410561
public class MinicrmPermissionService extends PermissionService implements IPermissionService {
  protected boolean acceptClassName(Bundle bundle, String className) {
    return className.indexOf("Permission") >= 0;
You will need to restart your server application.
Because of the higher priority, this implementation of IPermissionService will be selected, instead of the default one proposed with Kepler 3.9.0. With 3.9.1, the default implementation will have the correction contained in {{Bug|410625}}.

Revision as of 03:16, 1 October 2013

Wiki Home
Scout Tutorial
Permissions are created for you in the background by the SDK as you build your application, but they don't seem to have any effects. That's because by default, you're using the "anonymous" security filter and because you're being granted the "all" permission. This chapter shows you how to change that.
This page is an optional addition to the Minicrm Step-by-Step Tutorial and uses it as a starting point.


What is this chapter about?

This chapter is about authorization and authentication.

When creating forms and table pages, the wizards have always created Permission classes in the background:

  • CreateCompanyPermission
  • ReadCompanyPermission
  • UpdateCompanyPermission
  • DeleteCompanyPermission (actually, you will have to create this permission yourself if you implement a delete menu)

We want to create an Administration View where Users get assigned Roles. These Roles have Permissions. When a user logs in, the appropriate Permissions are loaded.

For this to work, users must be authenticated. We'll add a SecurityFilter to handle this.

This chapter assumes that you're pretty proficient at creating tables, forms and services. No more hand-holding. :)


The Apache Derby example database already contains the following tables:

---------  ---------------  ---------

The PERSON table has a USERNAME column.

Let us create two roles before we get started:

INSERT INTO minicrm.ROLE (role_nr, name) VALUES (1, 'Administrator');
INSERT INTO minicrm.ROLE (role_nr, name) VALUES (2, 'Standard');

If you want to take a look at the database using a command line tool, check this how-to: Modify a derby database.


Create a new Lookup Call RoleLookupCall.

The RoleLookupService uses this statement:

    return "" +
        "SELECT  ROLE_NR, " +
        "        NAME " +
        "FROM    ROLE " +
        "WHERE   1=1 " +
        "<key>   AND ROLE_NR = :key </key> " +
        "<text>  AND UPPER(NAME) LIKE UPPER(:text||'%') </text> " +
        "<all> </all> ";

Person Form

Create a Person Form and a Person Service to create and edit persons. Make sure you use the same class names if you want to copy and paste the SQL statements later in this section.

Label Class Name Column Name Type
Name NameField LAST_NAME String
First Name FirstNameField FIRST_NAME
Employer EmployerField COMPANY_NR SmartField (CompanyLookupCall)
Username UsernameField USERNAME String
Roles RolesField USER_ROLE.ROLE_NR ListBox (RoleLookupCall, Grid H 4)


Add a "New Person..." and a "Edit Person..." menu to the PersonTablePage.

protected void execAction() throws ProcessingException {
  PersonForm form = new PersonForm();
  if (form.isFormStored()) {
public void execAction() throws ProcessingException {
  PersonForm form = new PersonForm();
  if (form.isFormStored()) {


Here are the SQL statements you will need.


SQL.selectInto("" +
    "FROM   PERSON " +
    "INTO   :personNr"
    , formData);
SQL.insert("" +
    "VALUES (:personNr, :name, :firstName, :employer, :username)"
    , formData);
SQL.insert("" +
    "VALUES (:personNr, :{roles})"
    , formData);


SQL.selectInto("" +
    "       FIRST_NAME, " +
    "       COMPANY_NR, " +
    "       USERNAME " +
    "FROM   PERSON " +
    "WHERE  PERSON_NR = :personNr " +
    "INTO   :name, " +
    "       :firstName, " +
    "       :employer, " +
    "       :username"
    , formData);
SQL.select("" +
    "WHERE USER_NR = :personNr " +
    "INTO :roles"
    , formData);


SQL.update("" +
    "       LAST_NAME = :name, " +
    "       FIRST_NAME = :firstName, " +
    "       COMPANY_NR = :employer, " +
    "       USERNAME = :username " +
    "WHERE  PERSON_NR = :personNr"
    , formData);
SQL.delete("" +
    "WHERE  USER_NR = :personNr "
    , formData);
SQL.insert("" +
    "VALUES (:personNr, :{roles})"
    , formData);


If you're working in a multilingual environment, this is what it might look like:


Administration Outline

Create the following outline on the client side:

Administration Outline   <-- Create this outline only, the tables will be created soon
 ├─Role Table Page
 │  │
 │  └─Permission Table Page
 └─Permission Table Page

Additional table pages might be useful: which roles use a particular permission? which users have a particular role? These are left as an exercise for the reader.

Invisible Outline?
If you create a new outline in the folder All Outlines you will not see it when you restart the client. You should create a new outline beneath your Desktop instead. The SDK will not only create an outline for you, it will also register it on the Desktop and it will create a button for it.

Permission Table Page and Outline Service

Create the PermissionTablePage in AdministrationOutline, on the client side.

We'll be using this table in two places, thus we need a variable for the role (RoleNr).

If a role is provided, we need a service on the server side to provide these. Create a new outline service (AdministrationOutlineService) with an operation to get all the roles (getPermissionTableData) with a single argument of type Long (roleNr).

public Object[][] getPermissionTableData(Long roleNr) throws ProcessingException {
  return SQL.select("" +
      "WHERE ROLE_NR = :roleNr "
      , new NVPair("roleNr", roleNr));

If no role is provided, we list all the permissions. These are all available on the client. We don't need service on the server side to fetch them. Thus, on the client side, things look a bit different. Here's execLoadTableData for the newly created PermissionTablePage.

protected Object[][] execLoadTableData(SearchFilter filter) throws ProcessingException {
  if (getRoleNr() == null) {
    ArrayList<String> rows = new ArrayList<String>();
    BundleClassDescriptor[] permissions = SERVICES.getService(IPermissionService.class).getAllPermissionClasses();
    for (int i = 0; i < permissions.length; i++) {
      if (permissions[i].getBundleSymbolicName().contains("minicrm")) {
      else {
	// Skip bookmark permissions and other permissions that are not specific to our application
    Object[][] data = new Object[rows.size()][1];
    for (int i = 0; i < rows.size(); i++) {
      data[i][0] = rows.get(i);
    return data;
  else {
    return SERVICES.getService(IAdministrationOutlineService.class).getPermissionTableData(getRoleNr());

Don't forget to create a column for your table page, and the RoleNr (Long) variable!

This is what you'd like to see:

Minicrm Administration Permissions.png

No Permissions?
If you don't see any permissions, then you have to move your permissions from the current package to org.eclipsescout.demo.minicrm.shared.security

(Using the Swing client because we will have to create additional menus to switch outlines when using SWT.)

Role Table Page and Outline Service

Create a new table page in the administration outline (RoleTablePage) with two columns (non-displayable RoleNr of type Long and a String column called Role).

If you want to change the order of the child tapes, edit the execCreateChildPages method of the AdministrationOutline.

Add a new service operation to the AdministrationOutlineService called getRoleTableData. This one is very simple:

public Object[][] getRoleTableData() throws ProcessingException {
  return SQL.select("" +
      "FROM ROLE");

Use it on the execLoadTableData operation of the table page:

protected Object[][] execLoadTableData(SearchFilter filter) throws ProcessingException {
  return SERVICES.getService(IAdministrationOutlineService.class).getRoleTableData();

Add the PermissionTablePage as a child to the RoleTablePage. Note how the SDK already guessed that you will want to pass the primary of the current row to the child page:

protected IPage execCreateChildPage(ITableRow row) throws ProcessingException {
  PermissionTablePage childPage = new PermissionTablePage();
  return childPage;

If everything worked as intended, this is how it should look:

Minicrm Administration Roles.png

No data is visible because the permissions haven't been assigned to roles, yet. This will be our next task.

Assigning Permissions to Roles

We will create a menu which calls a tiny form to assign one or more permissions to a role. The form will contain nothing but a smart field with roles.

Let's start with the form.

Create a new form called AssignToRoleForm; do not create am Id (no AssignToRoleNr). On the second page of the wizard, get rid of the ModifyHandler, the ReadAssignToRolePermission and the UpdateAssignToRolePermission.

Add a smart field RoleField using LookupCall RoleLookupCall.

Add a variable of type String called Permission. Now do something which the SDK doesn't do for you: change the type of m_permission from String to String[] and change getPermission and setPermission to match.

Switch to the AssignToRoleService and remove the load and store operations. (You may have to remove them from the interface IAssignToRoleService as well.)

For the moment, there is nothing to do for the prepareCreate operation. For the create operation, use the following statement:

SQL.insert("" +
    "VALUES (:role, :{permission})"
    , formData);

Switch to the PermissionTablePage and add a menu called AssignToRoleMenu. Have it start the AssignToRoleForm and call the NewHandler. Mark the menu as both a Single Selection Action and a Multi Selection Action. Change the execAction as follows:

protected void execAction() throws ProcessingException {
  AssignToRoleForm form = new AssignToRoleForm();
  if (form.isFormStored()) {

Ideally, this is what it will look like:

Minicrm Assign To Role.png

Select all the permissions and assign them to the Standard role.

Here's what you should get:

Minicrm Role With Permissions.png

Removing Permissions

Create a new permission called RemoveAssignToRolePermission (in the shared section) with super class BasicPermission.

Create a new operation void remove (Long roleNr, String[] permission) for AssignToRoleService.

public void remove(Long roleNr, String[] permission) throws ProcessingException {
  if (!ACCESS.check(new RemoveAssignToRolePermission())) {
    throw new VetoException(TEXTS.get("AuthorizationFailed"));
  SQL.insert("" +
      "WHERE ROLE_NR = :roleNr " +
      "AND PERMISSION_NAME = :{permission} "
      , new NVPair("roleNr", roleNr)
      , new NVPair("permission", permission));

SQL statements and collections: In this particular case, we could have skipped the braces and written AND PERMISSION_NAME = :permission. That's because the framework will detect that :permission refers to something with multiple values and will rewrite the statement by inserting ANY! The result will be AND PERMISSION_NAME = ANY ('FooPermission', 'BarPermission').

Create a new RemovePermissionFromRoleMenu for the PermissionTablePage.

protected void execAction() throws ProcessingException {
  SERVICES.getService(IAssignToRoleService.class).remove(getRoleNr(), getTable().getPermissionColumn().getSelectedValues());

Make it visible only when permissions below a role are shown using execPrepareAction:

protected void execPrepareAction() throws ProcessingException {
  if (getRoleNr() == null) setVisible(false);

Missing Pieces

Things you can add to practice:

  1. a form to create, modify and remove roles
  2. make sure menus that will result in "permission denied" errors are invisible
  3. make table pages invisible that display information you are not allowed to read


Before you continue: make sure the administrator has the username "admin" and the administrator role. Make sure the administrator role has been assigned all permissions. Once we're done here you can lock yourself out of the application. If that happens, you will have to fix the permissions on the database.

Identifying Users

To get an idea of what goes on, find the ServerSession and change execLoadSession as follows:

protected void execLoadSession() throws ProcessingException{
  logger.warn("created a new session for "+getUserId());

When you start a new client, you'll see:

!MESSAGE eclipse.org.minicrm.server.ServerSession.execLoadSession(ServerSession.java:46) created a new session for anonymous

What user id? This is handled by security filters. Go to the config file of your server product (/eclipse.org.minicrm.server/products/development/config.ini). You'll see that the AnonymousSecurityFilter is active. IT provides the user id "anonymous".

Change the config.ini as follows:

### Servlet Filter Runtime Configuration
org.eclipse.scout.http.servletfilter.security.BasicSecurityFilter#realm=minicrm Development


Restart server and client.

You will be greeted with a login box! Provide one of the combinations from the config file. Username admin password manager for example.

The server log will show:

!MESSAGE eclipse.org.minicrm.server.ServerSession.execLoadSession(ServerSession.java:46) created a new session for admin

In order to deny access to unknown people, change execLoadSession as follows:

protected void execLoadSession() throws ProcessingException {
  SQL.selectInto("" +
      "FROM PERSON " +
      "WHERE UPPER(USERNAME) = UPPER(:userId) " +
      "INTO :personNr ");
  if (getPersonNr() == null) {
    logger.error("attempted login by " + getUserId());
    throw new ProcessingException("Unknown User: " + getUserId(), new SecurityException("access denied"));
  logger.info("created a new session for " + getUserId());

Now you can attempt to login with a valid username/password combination and the system will check whether a person actually uses the usernames provided. By default, the three users in the demo database match the usernames in the config file. You need to add more combinations to the config file in order to test it.

Granting Permissions to Users

Find the AccessControlService class and take a look at the execLoadPermissions method:

protected Permissions execLoadPermissions() {
  Permissions permissions = new Permissions();
  permissions.add(new RemoteServiceAccessPermission("*.shared.*", "*"));
  //TODO fill access control service
  permissions.add(new AllPermission());
  return permissions;

This grants every user all permissions. We need to replace this with something based on database. The following example even has a backdoor for the user with id 1!

protected Permissions execLoadPermissions() {
  Permissions permissions = new Permissions();
  // calling services is free
  permissions.add(new RemoteServiceAccessPermission("*.shared.*", "*"));
  // backdoor: the first user may do everything?
  if (ServerSession.get().getPersonNr().equals(1L)) {
    logger.warn("backdoor used: person nr 1 was granted all permissions");
    permissions.add(new AllPermission());
  else {
    try {
      // get simple class names from the databse
      StringArrayHolder permission = new StringArrayHolder();
      SQL.selectInto("" +
	  "WHERE R.USER_NR = :personNr " +
	  "INTO :permission ",
	  new NVPair("permission", permission));
      // create a map from simple class names to qualified class names
      HashMap<String, String> map = new HashMap<String, String>();
      for (BundleClassDescriptor descriptor : SERVICES.getService(IPermissionService.class).getAllPermissionClasses()) {
	map.put(descriptor.getSimpleClassName(), descriptor.getClassName());
      // instantiate the real permissions and assign them
      for (String simpleClass : permission.getValue()) {
	try {
	  permissions.add((Permission) Class.forName(map.get(simpleClass)).newInstance());
	catch (Exception e) {
	  logger.error("cannot find permission " + simpleClass + ": " + e.getMessage());
    catch (ProcessingException e) {
      logger.error("cannot read permissions: " + e.getStackTrace());
  return permissions;

Add a logger field to the AccessControlService class as follow:

public class AccessControlService extends AbstractAccessControlService {
    private static IScoutLogger logger = ScoutLogManager.getLogger(AccessControlService.class);

If you log in, you'll notice a strange warning on the server console:

... cannot find permission CreateVisitPermission: null
... cannot find permission ReadVisitPermission: null
... cannot find permission UpdateVisitPermission: null

If you investigate the demo database, you'll note data junk in ROLE_PERMISSION and USER_ROLE for the non-existent roles 5 to 13.

If you really want to clean it up:

DELETE FROM minicrm.role_permission WHERE role_nr > 2;
DELETE FROM minicrm.user_role WHERE role_nr > 2;


As permissions are granted when the server is started, you need to restart your client and server in order for any changes to take effect.

In order to change that, you need to clear the cache whenever you make any changes. Add the following statement to all the operations of the AssignToRoleService:


Add the following to the store operation of the PersonService (there is no need to do it for create since there is no cached data to clear).


This will obviate the need to restart the server whenever permissions have changed.


  1. make sure the administrator has the administrator role
  2. make sure the administrator role has all permissions
  3. make sure the administrator has the username "admin"
  4. make sure the employee has the standard role
  5. make sure the standard role only has the two "read" permissions
  6. make sure the employee has the username "blake"
  7. restart client and server
  8. login as blake/blake
  9. you should be unable to create new companies and persons or and unable to edit existing ones

Minicrm Company Not Editable.png