Package org.skyway.spring.util.webservice.cxf

Source Code of org.skyway.spring.util.webservice.cxf.AuthenticateCredentialsHandler

/**
* Copyright 2007 - 2011 Skyway Software, Inc.
*/package org.skyway.spring.util.webservice.cxf;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;

import org.apache.ws.security.WSPasswordCallback;
import org.springframework.security.Authentication;
import org.springframework.security.AuthenticationException;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.context.SecurityContext;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.context.SecurityContextImpl;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;

/**
* Handles authentication of incoming web service calls by asking the spring
* authentication manager to authenticate the credentials.  If the credentials
* are valid, the SecurityContext is initialized and set.
*
* @author jperkins
*
*/
public class AuthenticateCredentialsHandler implements CallbackHandler {
 
  private AuthenticationManager authenticationManager;
 
  AuthenticateCredentialsHandler(AuthenticationManager authenticationManager) {
    super();
    this.authenticationManager = authenticationManager;
  }

  public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
    WSPasswordCallback passwordCallback = (WSPasswordCallback) callbacks[0];

    authenticate(passwordCallback);
  }

  @SuppressWarnings("deprecation")
  private void authenticate(WSPasswordCallback passwordCallback){
    String userName = passwordCallback.getIdentifer();
    String password = passwordCallback.getPassword();
   
    Authentication authentication = new UsernamePasswordAuthenticationToken(userName, password);
    try {
      authentication = authenticationManager.authenticate(authentication);
      if (authentication.isAuthenticated()) {
        // Set the security context
        SecurityContext securityContext = new SecurityContextImpl();
        securityContext.setAuthentication(authentication);
        SecurityContextHolder.setContext(securityContext);
      } else {
        throw new RuntimeException("Invalid credentials."); //$NON-NLS-1$
      }
    } catch (AuthenticationException e) {
      throw new RuntimeException("Invalid credentials."); //$NON-NLS-1$
    }
   
  }
}
TOP

Related Classes of org.skyway.spring.util.webservice.cxf.AuthenticateCredentialsHandler

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.