Чтобы использовать пользовательскую таблицу Liferay с полями электронной почты и пароля, вы должны изменить следующий фрагмент CAS deployerConfigContext.xml
:
<property name="authenticationHandlers">
<list>
<!-- | This is the authentication handler that authenticates services by
means of callback via SSL, thereby validating | a server side SSL certificate. + -->
<bean class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler" p:httpClient-ref="httpClient"></bean>
<bean class="org.jasig.cas.adaptors.jdbc.SearchModeSearchDatabaseAuthenticationHandler">
<property name="tableUsers">
<value>User_</value>
</property>
<property name="fieldUser">
<value>emailAddress</value>
</property>
<property name="fieldPassword">
<value>password_</value>
</property>
<property name="passwordEncoder">
<bean class="com.ccm.ci.cas.authentication.handler.LiferayPasswordEncoder">
<!-- Default Liferay Password Encryption is SHA algorithm. If someone changes it in liferay it have to been changed here-->
<constructor-arg name="encodingAlgorithm" value="SHA"></constructor-arg>
</bean>
</property>
<property name="dataSource" ref="dataSource"></property>
</bean>
</list>
</property>
И
настроить CAS со следующим классом для декодирования пароля, закодированного Liferay 6 (см. свойство кодировщика пароля в приведенном выше фрагменте).
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
import javax.validation.constraints.NotNull;
import org.jasig.cas.authentication.handler.PasswordEncoder;
import org.vps.crypt.Crypt;
/**
* To authenticate cas over Liferay 6.0.5 database using liferay 6.0.5 hashing
* algorithms.
*
*/
public class LiferayPasswordEncoder implements PasswordEncoder {
public static final String UTF8 = "UTF-8";
public static final String TYPE_CRYPT = "CRYPT";
public static final String TYPE_MD2 = "MD2";
public static final String TYPE_MD5 = "MD5";
public static final String TYPE_NONE = "NONE";
public static final String TYPE_SHA = "SHA";
public static final String TYPE_SHA_256 = "SHA-256";
public static final String TYPE_SHA_384 = "SHA-384";
public static final String TYPE_SSHA = "SSHA";
public static final DigesterImpl digesterImpl = new DigesterImpl();
@NotNull
private static String PASSWORDS_ENCRYPTION_ALGORITHM = TYPE_SHA;
public LiferayPasswordEncoder() {
}
public LiferayPasswordEncoder(final String encodingAlgorithm) {
PASSWORDS_ENCRYPTION_ALGORITHM = encodingAlgorithm;
}
public static final char[] saltChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./"
.toCharArray();
public static String encrypt(String clearTextPassword) {
return encrypt(PASSWORDS_ENCRYPTION_ALGORITHM, clearTextPassword, null);
}
public static String encrypt(String clearTextPassword,
String currentEncryptedPassword) {
return encrypt(PASSWORDS_ENCRYPTION_ALGORITHM, clearTextPassword,
currentEncryptedPassword);
}
public static String encrypt(String algorithm, String clearTextPassword,
String currentEncryptedPassword) {
if (algorithm.equals(TYPE_CRYPT)) {
byte[] saltBytes = _getSaltFromCrypt(currentEncryptedPassword);
return encodePassword(algorithm, clearTextPassword, saltBytes);
} else if (algorithm.equals(TYPE_NONE)) {
return clearTextPassword;
} else if (algorithm.equals(TYPE_SSHA)) {
byte[] saltBytes = _getSaltFromSSHA(currentEncryptedPassword);
return encodePassword(algorithm, clearTextPassword, saltBytes);
} else {
return encodePassword(algorithm, clearTextPassword, null);
}
}
protected static String encodePassword(String algorithm,
String clearTextPassword, byte[] saltBytes) {
try {
if (algorithm.equals(TYPE_CRYPT)) {
return Crypt.crypt(saltBytes, clearTextPassword.getBytes(UTF8));
} else if (algorithm.equals(TYPE_SSHA)) {
byte[] clearTextPasswordBytes = clearTextPassword
.getBytes(UTF8);
// Create a byte array of salt bytes appeneded to password bytes
byte[] pwdPlusSalt = new byte[clearTextPasswordBytes.length
+ saltBytes.length];
System.arraycopy(clearTextPasswordBytes, 0, pwdPlusSalt, 0,
clearTextPasswordBytes.length);
System.arraycopy(saltBytes, 0, pwdPlusSalt,
clearTextPasswordBytes.length, saltBytes.length);
// Digest byte array
MessageDigest sha1Digest = MessageDigest.getInstance("SHA-1");
byte[] pwdPlusSaltHash = sha1Digest.digest(pwdPlusSalt);
// Appends salt bytes to the SHA-1 digest.
byte[] digestPlusSalt = new byte[pwdPlusSaltHash.length
+ saltBytes.length];
System.arraycopy(pwdPlusSaltHash, 0, digestPlusSalt, 0,
pwdPlusSaltHash.length);
System.arraycopy(saltBytes, 0, digestPlusSalt,
pwdPlusSaltHash.length, saltBytes.length);
// Base64 encode and format string
return Base64.encode(digestPlusSalt);
} else {
return digesterImpl.digest(algorithm, clearTextPassword);
}
} catch (NoSuchAlgorithmException nsae) {
throw new SecurityException("LiferayPasswordEncryption error:"
+ nsae.getMessage(), nsae);
} catch (UnsupportedEncodingException uee) {
throw new SecurityException("LiferayPasswordEncryption error:"
+ uee.getMessage(), uee);
}
}
private static byte[] _getSaltFromCrypt(String cryptString) {
byte[] saltBytes = null;
try {
if (Validator.isNull(cryptString)) {
// Generate random salt
Random random = new Random();
int numSaltChars = saltChars.length;
StringBuilder sb = new StringBuilder();
int x = random.nextInt(Integer.MAX_VALUE) % numSaltChars;
int y = random.nextInt(Integer.MAX_VALUE) % numSaltChars;
sb.append(saltChars[x]);
sb.append(saltChars[y]);
String salt = sb.toString();
saltBytes = salt.getBytes(Digester.ENCODING);
} else {
// Extract salt from encrypted password
String salt = cryptString.substring(0, 2);
saltBytes = salt.getBytes(Digester.ENCODING);
}
} catch (UnsupportedEncodingException uee) {
throw new SecurityException(
"Unable to extract salt from encrypted password: "
+ uee.getMessage(), uee);
}
return saltBytes;
}
private static byte[] _getSaltFromSSHA(String sshaString) {
byte[] saltBytes = new byte[8];
if (Validator.isNull(sshaString)) {
// Generate random salt
Random random = new SecureRandom();
random.nextBytes(saltBytes);
} else {
// Extract salt from encrypted password
try {
byte[] digestPlusSalt = Base64.decode(sshaString);
byte[] digestBytes = new byte[digestPlusSalt.length - 8];
System.arraycopy(digestPlusSalt, 0, digestBytes, 0,
digestBytes.length);
System.arraycopy(digestPlusSalt, digestBytes.length, saltBytes,
0, saltBytes.length);
} catch (Exception e) {
throw new SecurityException(
"Unable to extract salt from encrypted password: "
+ e.getMessage(), e);
}
}
return saltBytes;
}
public String encode(String pwd) {
return encrypt(pwd);
}
}
В завершение добавьте следующие настроенные классы портала Liferay (их можно найти в источниках портала Liferay) в настроенный CAS (они используются вышеупомянутым LiferayPasswordEncoder):
Base64.java
CharPool.java
ClassLoaderObjectInputStream.java
Digester.java
DigesterImpl.java
StringBundler.java
StringPool.java
UnsyncByteArrayInputStream.java
UnsyncByteArrayOutputStream.java
Validator.java
ПРАВКА: добавлено завершено deployerConfigContext.xml
вопрос об ошибке и версии CAS:
Я использую CAS версии 3.4.5, а вы?
Вот мой полный файл deployerConfigContext.xml.Я думаю, что в вашем файле появилась ошибка при добавлении фрагмента выше.Фактически, отсутствующий компонент определяется в этом файле.Пожалуйста, попробуйте объединить следующий файл с вашим (учитывая различия в URL базы данных, имени пользователя и пароле и т. Д.):
<?xml version="1.0" encoding="UTF-8"?>
<!-- | deployerConfigContext.xml centralizes into one file some of the declarative
configuration that | all CAS deployers will need to modify. | | This file declares
some of the Spring-managed JavaBeans that make up a CAS deployment. | The beans declared
in this file are instantiated at context initialization time by the Spring | ContextLoaderListener
declared in web.xml. It finds this file because this | file is among those declared
in the context parameter "contextConfigLocation". | | By far the most common change
you will need to make in this file is to change the last bean | declaration to replace
the default SimpleTestUsernamePasswordAuthenticationHandler with | one implementing
your approach for authenticating usernames and passwords. + -->
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:sec="http://www.springframework.org/schema/security" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<bean id="propertyPlaceholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="searchSystemEnvironment" value="true"></property>
</bean>
<!-- | This bean declares our AuthenticationManager. The CentralAuthenticationService
service bean | declared in applicationContext.xml picks up this AuthenticationManager
by reference to its id, | "authenticationManager". Most deployers will be able to
use the default AuthenticationManager | implementation and so do not need to change
the class of this bean. We include the whole | AuthenticationManager here in the
userConfigContext.xml so that you can see the things you will | need to change in
context. + -->
<bean id="authenticationManager" class="org.jasig.cas.authentication.AuthenticationManagerImpl">
<!-- | This is the List of CredentialToPrincipalResolvers that identify what
Principal is trying to authenticate. | The AuthenticationManagerImpl considers them
in order, finding a CredentialToPrincipalResolver which | supports the presented
credentials. | | AuthenticationManagerImpl uses these resolvers for two purposes.
First, it uses them to identify the Principal | attempting to authenticate to CAS
/login . In the default configuration, it is the DefaultCredentialsToPrincipalResolver
| that fills this role. If you are using some other kind of credentials than UsernamePasswordCredentials,
you will need to replace | DefaultCredentialsToPrincipalResolver with a CredentialsToPrincipalResolver
that supports the credentials you are | using. | | Second, AuthenticationManagerImpl
uses these resolvers to identify a service requesting a proxy granting ticket. |
In the default configuration, it is the HttpBasedServiceCredentialsToPrincipalResolver
that serves this purpose. | You will need to change this list if you are identifying
services by something more or other than their callback URL. + -->
<property name="credentialsToPrincipalResolvers">
<list>
<!-- | UsernamePasswordCredentialsToPrincipalResolver supports the UsernamePasswordCredentials
that we use for /login | by default and produces SimplePrincipal instances conveying
the username from the credentials. | | If you've changed your LoginFormAction to
use credentials other than UsernamePasswordCredentials then you will also | need
to change this bean declaration (or add additional declarations) to declare a CredentialsToPrincipalResolver
that supports the | Credentials you are using. + -->
<bean class="org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver"></bean>
<!-- | HttpBasedServiceCredentialsToPrincipalResolver supports HttpBasedCredentials.
It supports the CAS 2.0 approach of | authenticating services by SSL callback, extracting
the callback URL from the Credentials and representing it as a | SimpleService identified
by that callback URL. | | If you are representing services by something more or other
than an HTTPS URL whereat they are able to | receive a proxy callback, you will need
to change this bean declaration (or add additional declarations). + -->
<bean class="org.jasig.cas.authentication.principal.HttpBasedServiceCredentialsToPrincipalResolver"></bean>
</list>
</property>
<!-- | Whereas CredentialsToPrincipalResolvers identify who it is some Credentials
might authenticate, | AuthenticationHandlers actually authenticate credentials. Here
we declare the AuthenticationHandlers that | authenticate the Principals that the
CredentialsToPrincipalResolvers identified. CAS will try these handlers in turn |
until it finds one that both supports the Credentials presented and succeeds in authenticating.
+ -->
<property name="authenticationHandlers">
<list>
<!-- | This is the authentication handler that authenticates services by
means of callback via SSL, thereby validating | a server side SSL certificate. + -->
<bean class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler" p:httpClient-ref="httpClient"></bean>
<bean class="org.jasig.cas.adaptors.jdbc.SearchModeSearchDatabaseAuthenticationHandler">
<property name="tableUsers">
<value>User_</value>
</property>
<property name="fieldUser">
<value>emailAddress</value>
</property>
<property name="fieldPassword">
<value>password_</value>
</property>
<property name="passwordEncoder">
<bean class="com.ccm.ci.cas.authentication.handler.LiferayPasswordEncoder">
<!-- Default Liferay Password Encryption is SHA algorithm. If someone changes it in liferay it have to been changed here-->
<constructor-arg name="encodingAlgorithm" value="SHA"></constructor-arg>
</bean>
</property>
<property name="dataSource" ref="dataSource"></property>
</bean>
</list>
</property>
</bean>
<!-- This bean defines the security roles for the Services Management application.
Simple deployments can use the in-memory version. More robust deployments will want
to use another option, such as the Jdbc version. The name of this should remain "userDetailsService"
in order for Spring Security to find it. -->
<!-- <sec:user name="@@THIS SHOULD BE REPLACED@@" password="notused" authorities="ROLE_ADMIN"
/> -->
<sec:user-service id="userDetailsService">
<sec:user name="@@THIS SHOULD BE REPLACED@@" password="notused" authorities="ROLE_ADMIN"></sec:user>
</sec:user-service>
<!-- Bean that defines the attributes that a service may return. This example uses
the Stub/Mock version. A real implementation may go against a database or LDAP server.
The id should remain "attributeRepository" though. -->
<bean id="attributeRepository" class="org.jasig.services.persondir.support.StubPersonAttributeDao">
<property name="backingMap">
<map>
<entry key="uid" value="uid"></entry>
<entry key="eduPersonAffiliation" value="eduPersonAffiliation"></entry>
<entry key="groupMembership" value="groupMembership"></entry>
</map>
</property>
</bean>
<!-- Sample, in-memory data store for the ServiceRegistry. A real implementation
would probably want to replace this with the JPA-backed ServiceRegistry DAO The name
of this bean should remain "serviceRegistryDao". -->
<bean id="serviceRegistryDao" class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl">
<property name="registeredServices">
<list>
<bean class="org.jasig.cas.services.RegisteredServiceImpl">
<property name="id" value="0"></property>
<property name="name" value="HTTP"></property>
<property name="description" value="Only Allows HTTP Urls"></property>
<property name="serviceId" value="http://**"></property>
</bean>
<bean class="org.jasig.cas.services.RegisteredServiceImpl">
<property name="id" value="1"></property>
<property name="name" value="HTTPS"></property>
<property name="description" value="Only Allows HTTPS Urls"></property>
<property name="serviceId" value="https://**"></property>
</bean>
<bean class="org.jasig.cas.services.RegisteredServiceImpl">
<property name="id" value="2"></property>
<property name="name" value="IMAPS"></property>
<property name="description" value="Only Allows HTTPS Urls"></property>
<property name="serviceId" value="imaps://**"></property>
</bean>
<bean class="org.jasig.cas.services.RegisteredServiceImpl">
<property name="id" value="3"></property>
<property name="name" value="IMAP"></property>
<property name="description" value="Only Allows IMAP Urls"></property>
<property name="serviceId" value="imap://**"></property>
</bean>
</list>
</property>
</bean>
<!-- Data source definition -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://10.4.2.14:3306/lportal_${user.name}</value>
</property>
<property name="username">
<value>${user.name}</value>
</property>
<property name="password">
<value>${user.name}</value>
</property>
<property name="initialSize" value="1"></property>
<property name="maxIdle" value="5"></property>
<property name="maxActive" value="50"></property>
<property name="maxWait" value="10000"></property>
<property name="validationQuery" value="select 1"></property>
<property name="testOnBorrow" value="false"></property>
<property name="testWhileIdle" value="true"></property>
<property name="timeBetweenEvictionRunsMillis" value="10000"></property>
<property name="minEvictableIdleTimeMillis" value="30000"></property>
<property name="numTestsPerEvictionRun" value="-1"></property>
</bean>
</beans>