加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 01:36:06 所属栏目:大数据 来源:网络整理
导读:我使用loadUserByUsername方法来验证用户,但是,我还需要验证允许的IP地址. 但是当我努力的时候 SecurityContextHolder.getContext().getAuthentication(); 得到null. 请指教,如何在验证用户时访问用户的客户端IP地址. 最佳答案 要解决您的问题,您应该实现自

我使用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)
    }
}

组态:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读