net.kamhon.ieagle.security.AuthenticationUtil.java Source code

Java tutorial

Introduction

Here is the source code for net.kamhon.ieagle.security.AuthenticationUtil.java

Source

/*
 * Copyright 2012 Eng Kam Hon (kamhon@gmail.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.kamhon.ieagle.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.kamhon.ieagle.exception.DataException;
import net.kamhon.ieagle.exception.InvalidCredentialsException;
import net.kamhon.ieagle.exception.ValidatorException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.NullRememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.TextEscapeUtils;

/**
 * <p>
 * Modified from <code>UsernamePasswordAuthenticationFilter</code> suit it to ieagle framework. The main purpose are
 * "TRY" remain original Spring Security features.
 * </p>
 * <p>
 * This class is not recommended to replace <code>UsernamePasswordAuthenticationFilter</code> in Spring Security because
 * it not fully customized as custom <code>UsernamePasswordAuthenticationFilter</code>
 * </p>
 * 
 * @author kamhon
 * @see UsernamePasswordAuthenticationFilter
 */
public class AuthenticationUtil extends UsernamePasswordAuthenticationFilter {
    public static final String BEAN_NAME = "authenticationUtil";

    private static final Log log = LogFactory.getLog(AuthenticationUtil.class);

    private UserDetailsService userDetailsService;

    private boolean postOnly = true;

    public UserDetails authenticate(HttpServletRequest request, HttpServletResponse response, String username,
            String password) {
        Authentication authResult;

        try {
            // onPreAuthentication(request, response);
            authResult = attemptAuthentication(request, response, username, password);
        } catch (AuthenticationException failed) {
            try {
                // Authentication failed
                unsuccessfulAuthentication(request, response, failed);
            } catch (Exception ex) {
                throw new ValidatorException(failed.getMessage());
            }

            if (failed instanceof BadCredentialsException)
                throw new InvalidCredentialsException("Invalid username or password");
            else
                throw new ValidatorException(failed.getMessage());

        } /*catch (IOException ex) {
          throw new DataException(ex);
          }*/

        try {
            successfulAuthentication(request, response, authResult);
        } catch (IOException e) {
            throw new DataException(e);
        } catch (ServletException e) {
            throw new DataException(e);
        }

        return userDetailsService.findUserDetailsByUsername(username);
    }

    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response,
            String username, String password) throws AuthenticationException {
        if (postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        /*String username = obtainUsername(request);
        String password = obtainPassword(request);*/

        if (username == null) {
            username = "";
        }

        if (password == null) {
            password = "";
        }

        username = username.trim();

        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
                password);

        // Place the last username attempted into HttpSession for views
        HttpSession session = request.getSession(false);

        if (session != null || getAllowSessionCreation()) {
            request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY,
                    TextEscapeUtils.escapeEntities(username));
        }

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    /*@Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException failed) throws IOException, ServletException {
    }*/

    /*
    private Authentication attemptAuthentication(HttpServletRequest request, String username, String password) {
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
        
    // Place the last username attempted into HttpSession for views
    HttpSession session = request.getSession(false);
        
    if (session != null || getAllowSessionCreation()) {
        // request.getSession().setAttribute(SPRING_SECURITY_LAST_USERNAME_KEY, TextUtils.escapeEntities(username));
    }
        
    // Allow subclasses to set the "details" property
    setDetails(request, authRequest);
        
    return this.getAuthenticationManager().authenticate(authRequest);
    }*/

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
            Authentication authResult) throws IOException, ServletException {
        if (log.isDebugEnabled()) {
            log.debug("Authentication success: " + authResult.toString());
        }

        SecurityContextHolder.getContext().setAuthentication(authResult);

        if (log.isDebugEnabled()) {
            log.debug(
                    "Updated SecurityContextHolder to contain the following Authentication: '" + authResult + "'");
        }

        /*
         * if (invalidateSessionOnSuccessfulAuthentication) {
         * SessionUtils.startNewSessionIfRequired(request,
         * migrateInvalidatedSessionAttributes, sessionRegistry); }
         * 
         * String targetUrl = determineTargetUrl(request);
         * 
         * if (log.isDebugEnabled()) {
         * log.debug("Redirecting to target URL from HTTP Session (or default): "
         * + targetUrl); }
         */

        // onSuccessfulAuthentication(request, response, authResult);

        getRememberMeServices().loginSuccess(request, response, authResult);

        // Fire event
        if (this.eventPublisher != null) {
            eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(authResult, this.getClass()));
        }
    }

    /**
     * Override the function to prevent validate on others properties like targetUrl and etc.
     */
    @Override
    public void afterPropertiesSet() {
        if (getRememberMeServices() == null) {
            setRememberMeServices(new NullRememberMeServices());
        }

        // super.afterPropertiesSet();
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}