2015-03-24 2 views
0

Я разрабатываю TAI, которые должны авторизовать пользователя в WebSphere Portal.Программно аутентифицировать пользователя в TAI

My TAI с помощью OpenID Connect получает всю информацию о пользователе, и я хочу построить какой-то контекст, передать его WAS и сообщить WAS, что он должен доверять этому контексту без локальной учетной записи.

Как я могу авторизовать пользователя в TAI без учетной записи пользователя в локальных хранилищах?

UPDATE:

Код:

String userid = "bob"; 
String uniqueid = "bob"; 

Hashtable hashtable = new Hashtable(); 
hashtable.put(AttributeNameConstants.WSCREDENTIAL_UNIQUEID, uniqueid); 
hashtable.put(AttributeNameConstants.WSCREDENTIAL_SECURITYNAME, userid); 
hashtable.put(AttributeNameConstants.WSCREDENTIAL_CACHE_KEY, uniqueid+"MyCustom"); 

Subject subject = new Subject(); 
subject.getPublicCredentials().add(hashtable); 
return TAIResult.create(HttpServletResponse.SC_OK, "ignored", subject); 

Вход:

[25.03.15 20:16:33:521 AMT] 00000043 ServiceLogger I com.ibm.ws.ffdc.IncidentStreamImpl initialize FFDC0009I: FFDC opened incident stream file WebSphere_Portal_00000043_15.03.25_20.16.33_0.txt 
[25.03.15 20:16:33:537 AMT] 00000043 ServiceLogger I com.ibm.ws.ffdc.IncidentStreamImpl resetIncidentStream FFDC0010I: FFDC closed incident stream file WebSphere_Portal_00000043_15.03.25_20.16.33_0.txt 
[25.03.15 20:16:33:677 AMT] 00000043 StorageApi E com.ibm.wps.policy.commands.StorageApi StorageApi EJQAB0064E: A Null argument was passed to the StorageApi constructor. 
[25.03.15 20:16:33:724 AMT] 00000043 PolicyService E com.ibm.wps.policy.services.PolicyService Error Occured while creating storageAPI EJQAB0064E: A Null argument was passed to the StorageApi constructor. 

FFDC:

------Start of DE processing------ = [3/25/15 20:16:33:474 AMT] , key = com.ibm.websphere.wim.exception.PropertyNotDefinedException com.ibm.ws.security.auth.ContextManagerImpl.runAs 4153 
Exception = com.ibm.websphere.wim.exception.PropertyNotDefinedException 
Source = com.ibm.ws.security.auth.ContextManagerImpl.runAs 
probeid = 4153 
Stack Dump = com.ibm.websphere.wim.exception.PropertyNotDefinedException: CWWIM0514W The 'dn' property is not defined. 

Для этой ошибки я нашел this information.

Но я не понимаю, что они хотят меня сделать ...

Описание:

У меня есть FederatedRepositories, где только один репозиторий LDAP.

UPDATE # 2:

Я сделал такой TAI на WAS 8.5.5.2 и там нет ошибок, просто белый экран. Я попробовал auth user «bob» с группой «wpsadmins». Существуют FederatedRepositories с одним файловым встроенным репозиторием.

UPDATE # 3:

Я написал специальное приложение для WAS, где я есть кнопка, которая делает запрос POST в сервлет.

Частично код:

if (req.getRemoteUser() == null) { 
    req 
      .setAttribute("errorMessage", 
        "<b>Error: Please log in before accessing PrintUserInfo.<b>"); 
    RequestDispatcher disp = getServletContext().getRequestDispatcher(
      "/login.jsp"); 
    disp.forward(req, resp); 
    return; 
} 
resp.setContentType("text/html"); 
PrintWriter out = new PrintWriter(resp.getOutputStream()); 

String id = WSSubject.getCallerPrincipal(); 
out.println("The WAS Subject layer thinks you are " + id); 
    Context ic = new InitialContext(); 
    Object objRef = ic.lookup("UserRegistry"); 
    UserRegistry userReg = (UserRegistry) PortableRemoteObject.narrow(
      objRef, UserRegistry.class); 
    out.println("<BR><BR>The user registry says your display name is: " 
      + userReg.getUserDisplayName(req.getUserPrincipal() 
        .getName())); 

    Subject subject = WSSubject.getCallerSubject(); 
    Set credSet = subject.getPublicCredentials(WSCredential.class); 
    //should be impossible. 
    if (credSet.size() > 1) { 
     System.out 
       .println("Expected only one WSCredential in Subject set"); 
     throw new Exception("Expected one WSCredential, found " 
       + credSet.size()); 
    } 
if (credSet.isEmpty()) { 
    System.out.println("Credential set is empty"); 
    throw new Exception("Found no credentials"); 
} 
//get one and only one element of Set 
Iterator iter = credSet.iterator(); 
WSCredential creds = (WSCredential) iter.next(); 
out.println("<BR><BR>Looking into your Subject your userid is " 
     + creds.getSecurityName()); 
out.println("<BR><BR>Looking into your Subject your uniqueid is " 
     + creds.getUniqueSecurityName()); 
out 
     .println("<BR><BR>Looking into your Subject I see these groups: "); 
//List groups = helper.getGroups(); 
List groups = creds.getGroupIds(); 
iter = groups.iterator(); 
while (iter.hasNext()) { 
    String gid = (String) iter.next(); 
    out.println("<BR>Group ID: " + gid); 
} 

Новая версия TAI:

String userid = "alisa"; 
String uniqueid = "bob"; 

// add admin group 

// stash in hashtable 
Hashtable hashtable = new Hashtable(); 


try { 
    InitialContext ctx = new InitialContext(); 
    UserRegistry reg =(UserRegistry)ctx.lookup("UserRegistry"); 
    String wpsadminsGroupUniqueId = reg.getUniqueGroupId("wpsadmins"); 
    List<String> groups = new ArrayList<String>(); 
    groups.add(wpsadminsGroupUniqueId); 
    hashtable.put(AttributeNameConstants.WSCREDENTIAL_GROUPS, groups); 
} catch (Exception e) { 
    System.out.println("EXCEPTION IN TAI"); 
    e.printStackTrace(); 
} 

hashtable.put(AttributeNameConstants.WSCREDENTIAL_UNIQUEID,uniqueid); 
hashtable.put(AttributeNameConstants.WSCREDENTIAL_SECURITYNAME,userid); 
hashtable.put(AttributeNameConstants.WSCREDENTIAL_CACHE_KEY,uniqueid+"MyCustom"); 

Subject subject = new Subject(); 
subject.getPublicCredentials().add(hashtable); 
return TAIResult.create(HttpServletResponse.SC_OK, "ignored", subject); 

Так что я получил от предмета я получаю мои полномочия, включает в себя USERID, UniqueID и групп из LDAP.

Результат:

The WAS Subject layer thinks you are alisa 

The user registry says your display name is: 

Looking into your Subject your userid is alisa 

Looking into your Subject your uniqueid is bob 

Looking into your Subject I see these groups: 
Group ID: group:domain:port/cn=wpsadmins,cn=CN,ou=OU,o=O,o=O,c=ru 

UPDATE # 4

Я добавил в TAI несколько групп и чем я разрешаю в Portal (я думаю), но я вижу только белый экран без ничего. Что не так?

UPDATE # 5

И WPS дает мне исключение:

[26.03.15 18:47:41:006 AMT] 0000004e DefaultLoginF E com.ibm.wps.auth.impl.DefaultLoginFilter doLoginWithExceptions WpsException occured: com.ibm.wps.services.authentication.exceptions.UserRetrieveException: EJPSD0008E: Exception occurred while retrieving the user [null] from the user registry. 

ответ

2

Вы должны создать полную тему, для более подробной проверки Advanced authentication in WebSphere Application Server.

Короче говоря вам нужно использовать подобный код:

String userid = "bob";//get from request 
String uniqueid = "bob"; 

// stash in hashtable 
Hashtable hashtable = new Hashtable(); 
hashtable.put(AttributeNameConstants.WSCREDENTIAL_UNIQUEID,uniqueid); 
hashtable.put(AttributeNameConstants.WSCREDENTIAL_SECURITYNAME,userid); 
// hashtable.put(AttributeNameConstants.WSCREDENTIAL_GROUPS,groups); 
hashtable.put(AttributeNameConstants.WSCREDENTIAL_CACHE_KEY,uniqueid+"MyCustom"); 

Subject subject = new Subject(); 
subject.getPublicCredentials().add(hashtable); 
return TAIResult.create(HttpServletResponse.SC_OK, "ignored", subject); 
+0

Этот код требует uniqueId. Но этот uniqueId извлекается из UserRegistry by userId. Таким образом, у меня нет учетной записи пользователя в UserRegistry, я не получаю uniqueId. – dikkini

+0

@ dikkini Нет, вы можете установить этот идентификатор пользователя самостоятельно в правильном формате, не получая его из реестра, проверьте это [сообщение] (http://stackoverflow.com/a/27721289/3701228), где я создаю и использую пользователя не существующий в репозитории. Этот пользователь будет обрабатываться как аутентифицированный, но будет сложно сопоставить его с чем-то другим, все аутентифицированным, если вы не получите группы из репозитория. – Gas

+0

Stack Dump = com.ibm.websphere.wim.exception.InvalidUniqueNameException: CWWIM1011E Неверное имя 'test'. – dikkini

0

На WPS Exception добавлены в Update # 5 WebSphere Portal требует UniqueID быть полным квалифицированным DN. В этом случае у вас есть только короткое имя. Портал выполняет поиск пользователя на VMM с использованием DN и ожидает, что WSCredential.getUniqueSecurityName() вернет DN.

Смежные вопросы