DevOps Zone is brought to you in partnership with:

Gaurav has posted 1 posts at DZone. View Full User Profile

Steps to Enable OpenID Authentication in Spring-Security Application

05.26.2014
| 8870 views |
  • submit to reddit

A) Changes in spring-Security.xml

1. To enable OpenID authentication along with normal username password login, add

  <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>

to the  <http> element where form-login is defined.

2. Add

<authentication-provider user-service-ref="userAuthenticationProvider"/>

as child element to <authentication-manager>.

3. Define bean alias

<beans:alias name="customUserDetailsService" alias="userAuthenticationProvider"/>

4. Define “authenticationFailureHandlerbean.

<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.  Define  “authenticationSuccessHandler” bean.

  (No need to define authenticationSuccessHandler if you have defined 

  authenticationSuccessHandler for form-login)

<beans:bean id="authenticationSuccessHandler"

    class="com.hcentive.portal.employer.service.impl.CustomSuccessHandler">

    <beans:property name="companyInfoURL" value="/register/companyInformation"/>

</beans:bean>

6. Define customUserDetailsService bean.

<beans:bean id="customUserDetailsService" 

  class="com.hcentive.portal.employer.service.impl.CustomUserDetailsService"/>

B) Sample Implementation of beans defined in config file.

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);

  }

C) JSP changes.

1) Add following code to login page.

 <c:url var="googleLogoUrl" value="/resources/google-logo.png" />

  <img src="${googleLogoUrl}"></img>

  <form action="j_spring_openid_security_check" method="post">

  For Google users:

    <input name="openid_identifier" type="hidden"

  value="https://www.google.com/accounts/o8/id"/>

  <input type="submit" value="Sign with Google"/>

  </form>

D) Steps to Test Application:

1. On click of "Sign with Google" button it should redirect to Google login page.

2. After successful authentication with Google use should come to landing page.

 

Published at DZone with permission of its author, Gaurav Shukla.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Tred Tucla replied on Tue, 2014/10/07 - 2:41am

Hi,

I am trying to implement this openId and spring security integration but till not able to make it working.

I have added httpClient and guice.jar but still giving different errors. Can  you plz provide the working demo of

openId and spring secuirty.


Thanks in advace

Gaurav Shukla replied on Tue, 2014/10/07 - 9:29am in response to: Tred Tucla

what is the error you are getting?

Tred Tucla replied on Wed, 2014/10/08 - 1:11am in response to: Gaurav Shukla

 Hi,

Actually I am gettting the ClassNotFoundException- com.google.inject.provider.I have added httpClient.jar and Spring openId jar.But same exception occurs , can u plz help by providing the working demo or all required jars. Actually I am using this with GWT-Spring-HIbernate..

Thanks

Tred Tucla replied on Mon, 2014/10/13 - 5:21am

 Hi Gaurav,

I have resolved all the exception, Now openId auth working fine.But there is one issue that when loadUserByUsername(String username) -customUserDetailService - this function is called from openIdAuthenticationProvider then the params username contain the val as http://www.google.com/o8/id=HD&H*HJJD7HFRR567G, hence no user inforamtion is retrived from the database with such username value. So can u plz help me so that this param username must have the proper email address through which I can retrieve the proper user info from the database.

Thanks in advace..

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.