Аутентификация по IP-адресу в Spring 3.1: самый умный способ сделать это?

Я реализовал аутентификацию LDAP, используя Spring Security 3.1. Мой файл security.xml для этого размещен ниже.

Мне нужно изменить процесс аутентификации таким образом, чтобы, если пользователь заходит на сайт с IP-адреса из «белого списка» (хранящегося в таблице базы данных), этот пользователь должен был автоматически аутентифицироваться с помощью Spring 3.1, а затем перенаправляться подальше от экрана входа в систему (это не моя идея, мне так сказали).

Если пользователь не принадлежит ни к одному из IP-адресов, внесенных в белый список, то он/она должны быть принудительно пройдены аутентификация LDAP на странице входа.

Я новичок в Spring и Spring Security, поэтому я обратился к Справочной документации Spring 3.1и прочитал весь раздел I. Там я прочитал совет, что если у вас есть какие-либо особые потребности в аутентификации, вам следует читайте Раздел II Архитектура и реализация . Я делал это очень медленно и делал заметки.

Однако, поскольку я новичок во всем этом, я не уверен, что полностью понимаю, что мне нужно сделать, и как лучше всего это сделать.


Обновление 3: я получил скелетный код для работы, вот файлы, которые у меня получились


Моя собственная реализация AuthenticationProvider для аутентификации по IP-адресу

// Authentication Provider To Authenticate By IP Address With Allowed IPs
// Stored in a db table


package acme.com.controller.security;

//import acme.com.controller.security.CustomUserInfoHolder;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
import org.springframework.security.core.authority.mapping.NullAuthoritiesMapper;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;

import org.apache.log4j.Logger;


public class CustomIPAddressAuthenticationProvider implements AuthenticationProvider
{

    private static final Logger logger = Logger.getLogger(CustomIPAddressAuthenticationProvider.class);
    private GrantedAuthoritiesMapper authoritiesMapper = new NullAuthoritiesMapper();


    @Override
    public Authentication authenticate(Authentication authentication)
    throws AuthenticationException {


        WebAuthenticationDetails wad = null;
        String userIPAddress         = null;
        boolean isAuthenticatedByIP  = false;

        // Get the IP address of the user tyring to use the site
        wad = (WebAuthenticationDetails) authentication.getDetails();
        userIPAddress = wad.getRemoteAddress();


        logger.debug("userIPAddress == " + userIPAddress);

        // Compare the user's IP Address with the IP address in the database
        // stored in the USERS_AUTHENTICATED_BY_IP table & joined to the
        // USERS tabe to make sure the IP Address has a current user
        //isAuthenticatedByIP =  someDataObject.hasIPAddress(userIPAddress);
        isAuthenticatedByIP = true;


        // Authenticated, the user's IP address matches one in the database
        if (isAuthenticatedByIP)
        {

            logger.debug("isAuthenticatedByIP is true, IP Addresses match");
            UserDetails user = null;


            UsernamePasswordAuthenticationToken result = null;

            result = new UsernamePasswordAuthenticationToken("John Principal",
                                                              "PlaceholderPWE"); 

            result.setDetails(authentication.getDetails());

            return result;
        }


        // Authentication didn't happen, return null to signal that the 
        // AuthenticationManager should move on to the next Authentication provider
        return null;
    }


    @Override
    public boolean supports(Class authentication)
    {
        // copied it from AbstractUserDetailsAuthenticationProvider
        return(UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }

}

Мой файл *-security.xml



    
    
    
    
    




    
        

        
        
    



    


    


    
        
        
        
    



12
задан Steve 25 April 2012 в 17:47
поделиться