А) Изменения в spring-Security.xml
1. Чтобы включить аутентификацию OpenID вместе с обычным логином с паролем, добавьте
<openid-login
authentication-failure-handler-ref="authenticationFailureHandler"
default-target-url="/"
authentication-success-handler-ref="authenticationSuccessHandler"
user-service-ref="customUserDetailsService" >
<attribute-exchange identifier-match="https://www.google.com/.*">
<openid-attribute name="axContactEmail" type="http://axschema.org/contact/email"
required="true"/>
<openid-attribute name="oiContactEmail" type="http://schema.openid.net/contact/email"
required="true"/>
<openid-attribute name="axNamePersonFullname" type="http://axschema.org/namePerson"
required="true"/></attribute-exchange>
</openid-login>
к элементу <http>, где определяется форма входа в систему.
2. Добавить
<authentication-provider user-service-ref="userAuthenticationProvider"/>
как дочерний элемент для <authentication-manager>.
3. Определите псевдоним бина
<beans:alias name="customUserDetailsService" alias="userAuthenticationProvider"/>
4. Определите bean-компонент « authenticationFailureHandler».
<beans:bean id="authenticationFailureHandler"
class="com.hcentive.portal.employer.service.impl.CustomFailureHandler">
<beans:property name="defaultFailureUrl" value="/access-denied"/>
<beans:property name="companyInfoURL" value="/register/companyInformation" />
</beans:bean>
5. Определите bean-компонент « authenticationSuccessHandler ».
(Нет необходимости определять authenticationSuccessHandler, если вы определили
authenticationSuccessHandler для формы входа в систему )
<beans:bean id="authenticationSuccessHandler"
class="com.hcentive.portal.employer.service.impl.CustomSuccessHandler">
<beans:property name="companyInfoURL" value="/register/companyInformation"/>
</beans:bean>
6. Определите bean-компонент customUserDetailsService.
<beans:bean id="customUserDetailsService"
class="com.hcentive.portal.employer.service.impl.CustomUserDetailsService"/>
Б) Пример реализации bean-компонентов, определенных в конфигурационном файле.
1. CustomUserDetailsService
publicclass CustomUserDetailsService implements UserDetailsService,
{
/**
* Retrieves a user record containing the user's credentials and access.
*/
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException, DataAccessException {
final String userIdentifier = username.split("=")[1];
try{
//provide implementation to search user with username in database and
// return a user of type UserDetails
} catch (Exception e) {
//if user not found in database throw exception
thrownew UsernameNotFoundException("Error in retrieving user");
}
}
}
2. AuthenticationFailureHandle
publicclass CustomFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Override
publicvoid onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
if (exception instanceof UsernameNotFoundException
&& exception.getAuthentication() instanceof
OpenIDAuthenticationToken) {
OpenIDAuthenticationToken token = (OpenIDAuthenticationToken) exception
.getAuthentication();
if (OpenIDAuthenticationStatus.SUCCESS.equals(token.getStatus())) {
// getting attributes passed by google/openID provider
final List<OpenIDAttribute> attrList = token.getAttributes();
String username = (String) token.getPrincipal();
//provide implementation to create user from information passed from
//openID provider and save this user in database
//then redirect to redirectURL.
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
redirectStrategy.sendRedirect(request, response, “redirectURL”);
} else {
super.onAuthenticationFailure(request, response, exception);
}
}
3. AuthenticationSuccessHandler
publicclass CustomSuccessHandler extends
SavedRequestAwareAuthenticationSuccessHandler {
@Override
publicvoid onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication)
throws ServletException, IOException {
//provide implementation to set user data in session
//redirecting to landing page
getRedirectStrategy().sendRedirect(request, response, “landingpageURL”);
}
super.onAuthenticationSuccess(request, response, authentication);
}
В) JSP меняется.
1) Добавьте следующий код на страницу входа.
<c:url var="googleLogoUrl" value="/resources/google-logo.png" />
<img src="${googleLogoUrl}"></img>
<form action="j_spring_openid_security_check" method="post">
Для пользователей Google:
<input name="openid_identifier" type="hidden"
value="https://www.google.com/accounts/o8/id"/>
<input type="submit" value="Sign with Google"/>
</form>
D) Шаги для тестирования приложения:
1. При нажатии кнопки «Подписать с Google» он должен перейти на страницу входа в Google.
2. После успешной аутентификации с помощью Google следует зайти на целевую страницу.