微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用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

原文地址:https://www.jb51.cc/spring/432543.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐