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

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

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

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

Я новичок в Spring и Spring безопасности, поэтому я перешел в Spring 3.1 Reference Documentation и прочитал все Раздел 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 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 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<? extends Object> authentication)
    {
        // copied it from AbstractUserDetailsAuthenticationProvider
        return(UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }

}

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

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:s="http://www.springframework.org/schema/security"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.1.xsd">

    <s:http pattern="/login*" security="none"/>
    <s:http pattern="/search*" security="none"/>
    <s:http pattern="/css/**" security="none"/>
    <s:http pattern="/js/**" security="none"/>
    <s:http pattern="/images/**" security="none"/>




    <s:http auto-config="true" use-expressions="true">
        <s:intercept-url pattern="/**" access="isAuthenticated()" />

        <s:form-login login-page="/login"
          authentication-failure-url="/loginfailed" />
        <s:logout logout-success-url="/logout" />
    </s:http>



    <s:ldap-server url = "ldap://ldap-itc.smen.acme.com:636/o=acme.com"/>


    <bean id="customIPAddressAuthenticationProvider" class="com.acme.controller.security.CustomIPAddressAuthenticationProvider" />


    <s:authentication-manager>
        <!-- Proposed: Custom Authentication Provider: Try To Authenticate BY IP Address First, IF NOT, Authenticate WiTh THE LDAP Authentication Provider -->
        <s:authentication-provider ref="customIPAddressAuthenticationProvider" />
        <s:ldap-authentication-provider user-dn-pattern="uid={0},ou=People"/>
    </s:authentication-manager>


</beans>

Ответы

Ответ 1

Ваш подход кажется довольно хорошим, вы правы, думая, что Spring будет пытаться каждый AuthenticationProvider, пока он не получит успешный результат, поэтому в вашем случае вы должны определить своего провайдера на основе IP до поставщика LDAP.

В зависимости от вашей установки вы не можете получить объект WebAuthenticationDetails в своем вызове authentication.getDetails(). Если это так, вы должны добавить Spring RequestContextListener или RequestContextFilter к вашему web.xml. Затем вы сможете получить исходный IP-адрес с помощью класса RequestContextHolder и вызвать RequestContextHolder.getRequestAttributes().

Вам нужно только реализовать AuthenticationProvider, нет необходимости внедрять класс UserDetailsService, UserDetails или Authentication. Вы должны вернуть null, если вы не можете аутентифицировать пользователя через его IP-адрес. В этом случае Spring попробует поставщика LDAP. Если по какой-то причине вы не хотите передавать попытку на LDAP, вы должны выбросить AuthenticationException, которое остановит процесс и в итоге приведет к ошибке 403 для пользователя.

Надеюсь, это поможет:)