开发程序化登录以获取认证数据

可以使用 Java 认证和授权服务 (JAAS) 登录框架以通过应用程序获取认证数据。

关于此任务

通过使用 DefaultPrincipalMapping JAAS 上下文条目名称在专用凭证集(包含为 authData 元素配置的用户名和密码)中获取具有 javax.resource.spi.security.PasswordCredential 实例的主体集对象,应用程序可执行 JAAS 程序化登录。

过程

  1. server.xml 文件中添加 appSecurity-2.0passwordUtilities-1.0 功能部件。例如:
    <featureManager>
       <feature>appSecurity-2.0</feature>
       <feature>passwordUtilities-1.0</feature>
    </featureManager>
  2. server.xml 文件中配置 authData 元素。例如:
    <authData id="myAuthData" user="myUser" password="myPassword"/> <!-- password can also be encoded -->
    
    对配置中的密码进行编码。可使用 securityUtility encode 命令获取编码值。
  3. 使用 DefaultPrincipalMapping JAAS 登录上下文条目名称通过应用程序 servlet 或企业 bean 执行程序化登录(将映射别名替换为您需要的别名)。例如:
    HashMap map = new HashMap();
    map.put(com.ibm.wsspi.security.auth.callback.Constants.MAPPING_ALIAS, "myAuthData"); // Replace value with your alias.
    CallbackHandler callbackHandler = new com.ibm.wsspi.security.auth.callback.WSMappingCallbackHandler(map, null);
    LoginContext loginContext = new LoginContext("DefaultPrincipalMapping", callbackHandler);
    loginContext.login();
    Subject subject = loginContext.getSubject();
    Set<javax.resource.spi.security.PasswordCredential> creds = subject.getPrivateCredentials(javax.resource.spi.security.PasswordCredential.class);
    PasswordCredential passwordCredential = creds.iterator().next();
    注: 为简单起见,不显示错误处理。如果所请求认证别名不存在或格式错误,那么将返回 javax.security.auth.login.LoginException
  4. PasswordCredential 获取用户名和密码。例如:
    String userName = passwordCredential.getUserName();
    char[] password = passwordCredential.getPassword();
    // Do something with the userName and password.
  5. 如果启用了 Java 2 安全性,那么必须对应用程序授予 javax.security.auth.PrivateCredentialPermission。例如,在应用程序的 META-INF/permissions.xml 文件中授予该许可权以访问 PasswordCredential 对象:
    <?xml version="1.0" encoding="UTF-8"?>
    <permissions xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/permissions_7.xsd" version="7">
    
      <permission>
        <class-name>javax.security.auth.PrivateCredentialPermission</class-name>
        <name>javax.resource.spi.security.PasswordCredential * "*"</name>
        <actions>read</actions>
      </permission>
    
      <!-- Other permissions -->
    
    </permissions>

    有关 Java 2 安全性的更多信息,请参阅 Liberty:Java 2 安全性


用于指示主题类型的图标 任务主题

文件名:twlp_dev_prog_login_auth_data.html