【问题标题】:Spring security auto authorization for a given IP给定 IP 的 Spring Security 自动授权
【发布时间】:2019-02-06 10:38:00
【问题描述】:

在 Spring Security 中是否有可能(它是 Java,当然可能,所以问题是 - 是否有可能以某种相对轻松的方式)自动授权来自本地主机的所有请求(好的,一些给定的 IP)作为属于给定测试用户的请求。

例如在某些过滤器中 - 接受所有请求,检查 IP,如果它来自本地主机,请说类似 spring.authorizeAs("user")

【问题讨论】:

    标签: java web spring-security


    【解决方案1】:

    This answer 对于类似的问题可能会对您有所帮助。根据您的要求,您构建主体并将其手动设置为Security Context

    【讨论】:

    • 看起来有解决办法,我们试试吧。
    【解决方案2】:

    在我的情况下,答案如下

    @Component
    public class LocalAuthFilter implements Filter {
    
    
        @Autowired
        private UserDetailsService mng;
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
            if (("127.0.0.1".equals(req.getRemoteAddr())) &&
                    ("anonymousUser".equals(SecurityContextHolder.getContext().getAuthentication().getPrincipal()))) {
                UserDetails userDetails = mng.loadUserByUsername("user"); //my test user
                Authentication auth = new UsernamePasswordAuthenticationToken(
                        userDetails.getUsername(),
                        userDetails.getPassword(),
                        userDetails.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
            filterChain.doFilter(req, resp);
        }
    
        @Override
        public void destroy() {
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 2013-03-15
      • 2013-03-06
      • 2016-08-08
      • 2017-04-20
      • 2020-04-25
      • 1970-01-01
      相关资源
      最近更新 更多