How to test login/authentication with Arquillian - Java EE 7

前端 未结 1 915
走了就别回头了
走了就别回头了 2020-12-30 11:53

We have a Java EE 7 application and use Arquillian to test stuff. Now we want to check for some permissions of the currently logged in user. My question is quite basic, how

1条回答
  •  悲哀的现实
    2020-12-30 12:14

    Arquillian does not provide any support for defining realms. Instead you need to configure the realm in the container yourself. This is somewhat tricky when using an embedded Glassfish container but it is doable.

    I am assuming that secureJDBCRealm is a custom realm and not one of the standard/built-in Glassfish Realms. In order to configure a custom realm in a embedded Glassfish container you need to:

    1. Place a login.conf file on the test class path that references the realm. To do this add a config directory to your resources directory and place login.conf inside that directory. Your login.conf will look something like this

      secureJDBCRealm {
         com.blah.blah.LoginModule required;
      };
      
    2. Your custom realm along with any dependencies need to be on the test class path.

    3. You need to programmatically create the realm in glassfish. This can be done via org.glassfish.embeddable.CommandRunner. Luckily the Arquillian Embedded Container makes this available via JNDI which means you can do the following:

      @Resource(mappedName = "org.glassfish.embeddable.CommandRunner") CommandRunner commandRunner;
      
      public void configureLoginRealm() {
          CommandResult commandResult = commandRunner.run("create-auth-realm", "--classname=com.blah.blah.SecureJDBCRealm", "--property=jaas-context= secureJDBCRealm", "secure-JDBC-realm");
          log.debug(commandResult.getExitStatus().toString() + " " + commandResult.getOutput());
          Throwable throwable = commandResult.getFailureCause();
          if (throwable != null) {
              log.error(throwable.getMessage(), throwable);
          }
      }
      

      }

    4. You can then programmatically login with

      ProgrammaticLogin pl = new ProgrammaticLogin();
      String realmName = "secureJDBCRealm";
      try {
          pl.login("bob", "bob".toCharArray(), realmName, true);
      } catch (Exception e){
          e.printStackTrace();
      } finally {
          pl.logout();
      }
      

    0 讨论(0)
提交回复
热议问题