使用ip地址和用户名密码进行spring安全认证

我使用loadUserByUsername方法来验证用户,但是,我还需要验证允许的IP地址.

但是当我努力的时候

SecurityContextHolder.getContext().getAuthentication(); 

得到null.

请指教,如何在验证用户时访问用户的客户端IP地址.

最佳答案
解决您的问题,您应该实现自定义身份验证提供程序(可以基于DaoAuthenticationProvider或可以从头开始实现,等等).此身份验证提供程序应在Authentication Manager提供程序集中注册.此外,此提供程序将具有与上下文http请求相关的自动装配的HttpServletRequest类型属性.然后,当您通过该提供程序执行客户端身份验证时,可以通过调用HttpServletRequest.getRemoteAddr()来获取用户IP地址.
码:

/**
 * IP address based authentication provider
 */
@Service 
public class IPAddressBasedAuthenticationProvider extends AuthenticationProvider {

     /**
      * Context http request
      */
     @Autowired
     private HttpServletRequest request;

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

         String ipAddress = request.getRemoteAddr();
         //do authentication specific stuff (accessing users table in database,etc.)
         //return created authentication object (if user provided valid credentials)
    }
}

组态:

ecurity:http auto-config="true" authentication-manager-ref="authenticationManager" use-expressions="true"/>

ecurity.authentication.ProviderManager">
 

此外,您可以添加其他身份验证提供程序(如果需要).
希望这可以帮助.
链接AuthenticationProvider
ProviderManager

相关文章

这篇文章主要介绍了spring的事务传播属性REQUIRED_NESTED的原...
今天小编给大家分享的是一文解析spring中事务的传播机制,相...
这篇文章主要介绍了SpringCloudAlibaba和SpringCloud有什么区...
本篇文章和大家了解一下SpringCloud整合XXL-Job的几个步骤。...
本篇文章和大家了解一下Spring延迟初始化会遇到什么问题。有...
这篇文章主要介绍了怎么使用Spring提供的不同缓存注解实现缓...